Reputation: 837
UPDATE:
The issue was the div was in a div that was hidden, when divs are hidden length, offset(), position() don't work properly.
This should be simple.
I'm trying to test if a div exsists on the page after an ajax .html() output
if($('#'+mydiv).length != 1) { // do stuff }
there is only one problem, if the div your searching for is not there when (document).ready fires then .length doesn't see it.
Upvotes: 1
Views: 2617
Reputation: 837
Ensure your div isn't hidden when checking length. Usually, hidden div's can cause lots of problems.
Upvotes: 0
Reputation: 6587
I run into the exact same problem with the ticker after page content has been loaded using ajax - my solution was to use the livequery plugin : http://github.com/brandonaaron/livequery/downloads. I then use it in the following way:
$('.ticker').livequery(function() {
if ($(this).length > 0) {
var thisObj = $(this);
if (thisObj.length > 1) {
jQuery.each(thisObj, function() {
systemObject.tickerExe($(this));
});
} else {
systemObject.tickerExe(thisObj);
}
}
});
I hope this helps.
Upvotes: 1
Reputation: 11647
If you are performing an async request, which I assume you are (async:true
in JQuery) then you should be using size() in the success callback of your function, after the content has been added.
$.ajax({
url: requestUrl,
type: 'POST',
dataType: 'json',
data: {},
success: function(response) {
$('#container').html(response.data);
if($('someSearch').size() > 0)
alert('exists');
}
});
Upvotes: 2
Reputation: 1906
You could just use the size() method
if($('#'+mydiv).size() != 1) {
// do stuff
}
This recounts the number of matching elements in the DOM.
Upvotes: 3
Reputation: 570
You could use something like:
$('#loader').load('url', {variable1:var1}, function () {
if($('#'+mydiv).length != 1) {
// do stuff
}
});
That should look for anything loaded after your load call is finished loading.
Upvotes: 1