ghostCoder
ghostCoder

Reputation: 7655

jquery selection in context of a jQuery object

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?

Upvotes: 0

Views: 117

Answers (3)

WSkid
WSkid

Reputation: 2786

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 .media 0 results.

Take <div class="media">efg</div>'s children -- 0 children -- and look for .media 0 results.

Take <div class="nvid">qwr</div>'s children -- 0 children -- and look for .media 0 results.

To do it the DOM way, wrap it in a div and do your find:

var html = '<div class="media">abc</div>' + 
           '<div class="media">efg</div>' +
           '<div class="nvid">qwr</div>';
var obj = $(html);
//this fails:
$('div.media',obj).each(function(){console.log("found with jquery object");});

// this works as a single DOM object
var wrap = $('<div/>').append(obj).eq(0);
$('div.media',wrap).each(function(){console.log("found with DOM object");});

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 docs

obj.filter('.media').each(function(){console.log("found with Filter");});

Based on your comment you can do something like:

$(html).filter('.media').each(function(){
   var myDiv = $(this);
   // do stuff with myDiv.html();
});

You can checkout the jsfiddle here - slightly outdated now.

Upvotes: 1

TheBrain
TheBrain

Reputation: 5608

the problem is that the way you call your console.log(). it evaluates right there and shows found even if nothing is found. because you don't pass a reference to a function, you just call log('found')

you should have

jQuery('div.media', jq).each(function() { console.log("found") });

Upvotes: 0

pimvdb
pimvdb

Reputation: 154838

You must pass a function to .each, and you could better code along the lines of this this, because it isn't attached to the DOM:

jq.filter(function(){ return $(this).hasClass('media') })
  .each(function() { console.log("found"); });

Upvotes: 3

Related Questions