I have an on the fly (not part of the DOM document), HTML code. Something like-
<div class="media">
abc
</div>
<div class="media">
efg
</div>
<div class="nvid">
<div class="media">
qwr
</div>
</div>
now i make a jQuery obj for the above html using,
jq = jQuery(above html);
then i select the divs having class as ‘media’ by using the syntax-
jQuery('div.media', jq).each(console.log("found"));
now, ideally i should get three ‘found’ printed on the command line, but i am getting only one. any ideas, what i am missing?
Edited for clarity.
Behind the scenes using the core jQuery(selector, context) will perform a
.find(). Reading the docs on .find() it states it will search the current elements’ children.Meaning your call will do the following:
Take
<div class="media">abc</div>‘s children — 0 children — and look for.media0 results.Take
<div class="media">efg</div>‘s children — 0 children — and look for.media0 results.Take
<div class="nvid">qwr</div>‘s children — 0 children — and look for.media0 results.To do it the DOM way, wrap it in a div and do your find:
The reason this works is because we insert your html as children, and do the search on the parent container (wrapper) and it gets 3 children, and it matches 2 of those children.
To do it the
filter()way and return a NEW jquery object with just those elements: link to filter docsBased on your comment you can do something like:
You can checkout the jsfiddle here – slightly outdated now.