I have an ajax call that returns a HTML fragment. I am trying to select a div in that fragment before rendering.
An example of the HTML:
<div class="event-detail repBy-container">
<div class="copy">.....</div>
<div class="links">
....
</div>
<div class="contacts">
<div class="name-brand">....</div><div class="details">...., <a href="mailto:...@....">...</a></div>
</div>
</div>
Now the problem:
function ajaxReturn(data) {
alert($(data).find('.event-detail').length); <-- Returns 0
alert($(data).find('.copy').length); <-- Returns 1
}
Is this a bug or am I doing something wrong?
.find()
gets descendants only, not from the current level, you'd need .filter()
to get items from the current set (which is the root of what you returned), like this:
function ajaxReturn(data) {
alert($(data).filter('.event-detail').length); //<-- Returns 1
alert($(data).find('.copy').length); //<-- Returns 1
}
If you want .find()
to work in both cases, add the content to a parent container, like this:
function ajaxReturn(data) {
var parent = $("<div />").append(data);
alert(parent.filter('.event-detail').length); //<-- Returns 1
alert(parent.find('.copy').length); //<-- Returns 1
}
This is the expected behavior.
.event-detail
under your div and there isn't any. .copy
under your div and there is one.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With