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
1 Answer
Reset to default 7Just 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
});