3 hello<...">

Find each div with the specified class

var data='<div class="shout_msg"> <span class="username">3</span> <span class="message">hello</span> </div> <div class="shout_msg"> <span class="username">0</span> <span class="message">yo</span> </div> <div class="shout_msg"> <span class="username">0</span> <span class="message">hey</span> </div> <div class="shout_msg"> <span class="username">0</span> <span class="message">haha</span> </div>'; $(data).find(".shout_msg").each(function(index){ console.log($(this).find("span.username").text() ); }); 

It does not return anything. Basically, the data shown here in the variable comes from an AJAX request. But in any case, I am making a stupid mistake or something like that. Please correct me.

+4
source share
2 answers

In this case, you want to use filter , since you are not doing a search inside the objects.

 $(data).filter(".shout_msg").each(function(index){ console.log( $(this).find("span.username").text() ); }); 

Here is a brief demonstration for you.

http://jsbin.com/ocefeq/1/edit

+5
source

It is assumed that you use filter here

 $(data).filter(".shout_msg"). 

You need to access the first level of elements, but find will try to get elements that exclude the current level, and instead get descendants.

Check feed

+2
source

Source: https://habr.com/ru/post/1494608/


All Articles