5

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?

3 Answers 3

5

.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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that, it was driving me nuts
5

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.

Comments

0

It depends on what is being passed into the ajaxReturn function. ie what does data contain?

If it contains the HTML you quoted then this is expected behaviour. This is because the .find() method searches within the current context, not including it. If the outer div in your example is the outer div in data then .find() will be searching for .event-detail inside of that div.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.