curious1 curious1 - 6 months ago 17
jQuery Question

JQuery: find an element in a dynamically generated HTML snippet

I have the following code:

var snippet = $('<div><span class="findme">text</span></div><div class="findme2"></div>');

alert(snippet.find('.findme2').length);


The alert shows 0.

How can I find the findme2 div through JQuery? Assume that I cannot modify the structure of the above HTML snippet (for example: adding DIV to wrap the snippet)

Update

I have to use Jquery 1.11.x.

Answer

You need to use filter() otherwise it search inside the elements

var snippet = $('<div><span class="findme">text</span></div><div class="findme2"></div>');

alert(snippet.filter('.findme2').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Or wrap with an element and then use find()

var snippet = $('<div><span class="findme">text</span></div><div class="findme2"></div>');

alert($('<div>', {
  html: snippet
}).find('.findme2').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>