user1240679
user1240679

Reputation: 6979

Save the parents children in a var to append later

I have a markup in one of my website pages as follows:

<div id="mainPage">
   <div>
       <div><ul><li>etc.</li></ul>
   </div>
   <div>
       <div><ul><li>etc.</li></ul>
   </div>
</div>

What the above means is that there's a main div in my website which has the content. I want to take all the children of the particular div and save it in a var, since I want to use that var later for something like $('resurrectPage').append(someVar); where someVar has the dom elements from the main page div.

How can all the children of a particular element be selected and added to a var?

Upvotes: 1

Views: 149

Answers (4)

aNewStart847
aNewStart847

Reputation: 1076

If you only need the HTML you can save the HTML: var someVar = $("#mainPage").html(); and then append the HTML with the code you already have. Please tell me if I have misunderstood your question.

Upvotes: 0

user2404546
user2404546

Reputation:

$('#mainPage').html() would give you the entire thing in a string "<div> <div><ul><li>etc.</li></ul> </div> <div> <div><ul><li>etc.</li></ul> </div>"

$('#mainPage').children() would give you immidiate children [div,div]

$('#mainPage').find('.div') would giv =e you all the divs inside it [div,div,div,div]

Upvotes: 1

alt
alt

Reputation: 13907

I think you're looking for jQuery detach method...

http://api.jquery.com/detach/

It will remove an element and store its contents, ready to be re-appended:

var a = p = $("a").detach()

Upvotes: 0

HungryCoder
HungryCoder

Reputation: 7616

if #mainPage is your main div, you can get of it's children by

var someVar = $('#mainPage').children();

Official api page

Upvotes: 0

Related Questions