Reputation: 3484
I have a string which holds the innerHtml of an object (received via a call to $.html()
).
How can I create a jQuery object based on that string?
Upvotes: 2
Views: 153
Reputation: 536369
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()
.
Upvotes: 1
Reputation: 22770
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.
Upvotes: 1