Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible JQuery class selector bug

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?

like image 770
Magpie Avatar asked Nov 04 '10 16:11

Magpie


2 Answers

.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
}
like image 107
Nick Craver Avatar answered Nov 02 '22 17:11

Nick Craver


This is the expected behavior.

  • You are searching for .event-detail under your div and there isn't any.
  • You are searching for .copy under your div and there is one.
like image 23
cherouvim Avatar answered Nov 02 '22 18:11

cherouvim