admin管理员组文章数量:1426007
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 badges4 Answers
Reset to default 4The 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/
本文标签: javascriptselect from a variable with htmlwith jQueryStack Overflow
版权声明:本文标题:javascript - select from a variable with html, with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745463893a2659446.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论