javascript - select from a variable with html, with jquery - Stack Overflow

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

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!

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!

Share Improve this question asked Jun 15, 2011 at 18:02 elranuelranu 2,3126 gold badges31 silver badges55 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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);
});

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>');

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.

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/niklasvh/dLL5r/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745463894a4628830.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信