最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use jQuery to check if an element is added to page? - Stack Overflow

programmeradmin0浏览0评论

So I am using endless scrolling, and when I have scrolled x amount of pixels there will be added new objects to the page. But how can I use jQuery to check if a new element (class or id) is added to the page?

(I want to check this, because if a new element is added I want to do some jQuery on the new element).

So I am using endless scrolling, and when I have scrolled x amount of pixels there will be added new objects to the page. But how can I use jQuery to check if a new element (class or id) is added to the page?

(I want to check this, because if a new element is added I want to do some jQuery on the new element).

Share Improve this question asked Jun 22, 2013 at 1:31 alleguttaallegutta 5,64411 gold badges40 silver badges58 bronze badges 5
  • Do you mean a new element added dynamically on to the page? – PSL Commented Jun 22, 2013 at 1:33
  • Did my answer not help you? – Kylie Commented Jun 22, 2013 at 1:45
  • 1 @allegutta In that case do you have control over when the element is added on to the page. Also have a look at mutation observer. developer.mozilla/en-US/docs/Web/API/MutationObserver – PSL Commented Jun 22, 2013 at 1:47
  • @KyleK seems like OP is looking for a way to detect a new element added on to the page dynamially – PSL Commented Jun 22, 2013 at 1:47
  • Isn't your own code responsible for dynamically adding elements? – jahroy Commented Jun 22, 2013 at 2:08
Add a ment  | 

1 Answer 1

Reset to default 7

Just use .length, to check if it exists, after an append()

$('#elemId').length;

Like so...

if($('#elemId').length > 0){ //your code here };

Or write your own function....

jQuery.fn.Exists = function(){
    return jQuery(this).length > 0;
};

Then use it to return true or false...

if($('#elemId').Exists()){ //your code here };  

Or you can use the livequery() plugin...

$('#elemID').livequery(function()
{
// do things here like binding new events and stuff.
// this function is called when an object is added.
// check the API for the deletion function and so on.
});

I can't seem to find the plugin anymore, on the jQuery website, but it did exist at one point

You can also try DOMNodeInserted...

$(document).bind('DOMNodeInserted', function(e) {
console.log(e.target, ' was inserted');
});

You can use on()....if your selector will always be the same...

So for instance, say as you scroll you're always adding a new div called class="newDiv"....

Then the jquery you want to perform....if you want to bind an event to click...

$(document).on( 'click', '.newDiv', function(){ //your code here
 });
发布评论

评论列表(0)

  1. 暂无评论