How can I create a jQuery object from innerHtml?
I have a string which holds the innerHtml of an object (re开发者_运维技巧ceived via a call to $.html()
).
How can I create a jQuery object based on that string?
$(htmlString)
This will hold all of the elements in the string.
If you still have the original jQuery object you called the .html()
on, you can access its children directly by using the .children()
method:
var $children = $obj.children();
This will return them as jQuery array.
var newelement= $('<div/>');
newelement.html(htmlString);
This differs slightly from SLaks's answer in that it preserves direct text node children. jQuery's $(htmlString)
construction shortcut, like many of its features, only deals with Element nodes and not Text nodes.
So if htmlString
is 'foo<bar>bof</bar>zot'
, and you wanted to keep the foo
and the zot
, you'd have to do it this way.
Similarly with Xion's answer, if you wanted to keep direct text node children, you'd have to use the more-unusual contents()
method rather than children()
.
精彩评论