开发者

select from a variable with html, with jquery

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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜