最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论