1

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.

2
  • You should have wrapped your string in single quotes or escaped out the quotes as well var $html = $('<div id="a"><div id="b"><div id="c"></div></div></div>'); Commented Feb 19, 2011 at 19:14
  • @fudgey: I didnt done copy paste of my code. I just typed manually. I ll edit it now. Commented Feb 19, 2011 at 20:21

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

My problem is, the div#a and its descendent's are a string.
How is it a string? If it's on the page it's part of the DOM, which means you can access them based on their IDs. If it's not part of the page than jQuery can't help you: jQuery is for DOM manipulation, not string manipulation.
Did you noticed my update!!?? I think there should be a way to do it. I ll try to find it and post it here.
Sorry for the confusion, both append & html works for it. The problem is, $newHtml only holds the elements of #c. $html contains all, including inserted elements. :)
0

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.

2 Comments

@BoltClock Even though it tries to answer the question?
I have tried it. Both returns same jq obj. Because, i think, .find() will return only the found object.
0
var $newHtml = $('#c', $html).html(html);

1 Comment

It returns only #c and its elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.