user405398
user405398

Reputation:

Inserting html string into a jquery object?

I have the following structure:

var $html = $("<div id='a'><div id='b'><div id='c'></div></div></div>");

I want to insert the following into the $html structure under div #c:

var html = "<div id='d'><div id='e'><div id='f'></div></div></div>";

I tried the following:

var $newHtml = $($html).find("#c").append(html);

I thought now the variable $newHtml would point to div #a and all its descending elements including the newly appended ones.

However, $newHtml only contains the #c div and decendants.

How do I get the #a object and its descendents?

Update:

To clarify:

I have the jquery object $html and a string html.

I want to insert the html string into one the innermost element of the $html structure.

both append & html works for it. The problem is, $newHtml only holds the elements of #c. $html contains all, including inserted elements.

Upvotes: 1

Views: 5922

Answers (3)

pixeline
pixeline

Reputation: 17984

var $newHtml = $('#c', $html).html(html);

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 97004

You can just do

$('#c').append(html);

There's no reason to set the result to a variable. Almost all jQuery methods return a jQuery object, this allows you to chain methods together.

Upvotes: 2

sdleihssirhc
sdleihssirhc

Reputation: 42496

I think $html is already a jQuery object. so you don't need to use $($html).find, you can just do $html.find.

Also, I think you'll want to use the html method instead of append, though I could be wrong.

EDIT: Yeah, I was wrong. Append should work fine.

Upvotes: 0

Related Questions