1

I have html on a variable, how can I do a select on it and then an each on this variable? Example:

var ht = '<div id="1" class="pp">Hi</div><div id="2">Hola</div><div id="3" class="pp"> Bonjour</div>';
$(ht).find(".pp").each( function(i){
   var i = this.id;
   console.log(i);
});

of course this does not work. Thanks!

4 Answers 4

4

The problem with your code is that you have several sibling .pp elements that don't have a parent element. When you create a jQuery object with them, it creates a selection containing each of the .pp elements.

When you use find, it looks at descendant elements. The elements in the selection itself are not tested. You need to use filter instead, which tests the elements that are actually selected, not their descendants:

$(ht).filter(".pp").each( function(i){
   var i = this.id;
   console.log(i);
});
Sign up to request clarification or add additional context in comments.

Comments

1

Create an element from your HTML, and then operate on the element:

Change:

var ht = '<div id="1" class="pp">Hi</div><div id="2">Hola</div><div id="3" class="pp"> Bonjour</div>';

to:

var ht = $('<div id="one" class="pp">Hi</div><div id="two">Hola</div><div id="three" class="pp"> Bonjour</div>');

Comments

0

You need to actually create these elements as jQuery objects:

var div0 = $('<div />');
var div1 = $('<div />').addClass('pp').text('Bonjour');
div0.append(div1);
div0.find('.pp'); // == div1

This is obviously not ideal code, but it should get you going in the right direction.

3 Comments

Not true. This was indeed invalid before HTML5, but it works just fine.
@lonesomeday - interesting. i updated my answer. hopefully you can update your vote ;)
That hasn't really made your answer actually answer the question. You can build a jQuery object as the OP does -- you just need to make sure you're using the right traversing method.
0

Use .nextAll() instead of .find(). You can't use find() as it looks for the matched elements in descendants of the selection, but you want to look among them instead.

var ht = '<div id="1" class="pp">Hi</div><div id="2">Hola</div><div id="3" class="pp"> Bonjour</div>';


$(ht).nextAll("div.pp").each( function(i){

   var i = this.id;
   console.log(i);
});

http://jsfiddle.net/niklasvh/dLL5r/

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.