Elbek
Elbek

Reputation: 3484

How can I create a jQuery object from innerHtml?

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

Answers (3)

bobince
bobince

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

Xion
Xion

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

SLaks
SLaks

Reputation: 887375

$(htmlString)

This will hold all of the elements in the string.

Upvotes: 5

Related Questions