Possible jQuery class selection error

I have an ajax call that returns an HTML fragment. I am trying to select a div in this snippet before rendering.

HTML example:

<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 is:

function ajaxReturn(data) {
   alert($(data).find('.event-detail').length); <-- Returns 0
   alert($(data).find('.copy').length); <-- Returns 1
}

Is this a mistake or am I doing something wrong?

+5
source share
3 answers

.find()gets only descendants, not from the current level, you need .filter()to get elements from the current set (which is the root of what you returned), for example:

function ajaxReturn(data) {
   alert($(data).filter('.event-detail').length); //<-- Returns 1
   alert($(data).find('.copy').length); //<-- Returns 1
}

If you want to .find()work in both cases, add content to the parent container, for example:

function ajaxReturn(data) {
   var parent = $("<div />").append(data);
   alert(parent.filter('.event-detail').length); //<-- Returns 1
   alert(parent.find('.copy').length); //<-- Returns 1
}
+5
source

This is the expected behavior.

  • .event-detail div, .
  • .copy div .
+5

It depends on what is passed into the function ajaxReturn. those. what does it contain data?

If it contains the HTML code that you are quoting, then this is the expected behavior. This is because the method .find()searches in the current context, not including it. If the outer div in your example is the outer div in data, then it .find()will search .event-detailinside that div.

0
source

All Articles