Hi,
Below is my code which I am using to remove a div tag. I also want the script to add the same div tag later once certain conditions are meet. The div has some preloaded content too which I don't want to loose. I tried the add() function but it did not work for me. I even don't think append will work as I want to original div to reappear.

$('#wrapper1').remove();

Any help will be highly appreciated.

Cheers, Vishal

Vishal,

As it says in the jQuery API, jQuery.remove() returns jQuery , so you can do something like this:

var x = $('#myDiv').remove();
//.......
$('#myElement').append(x);//or .after() or .prepend() depending on how you need to insert x back into the DOM. Of course, like any javascript member, x must be in scope, or formally passed to a function that operates on it.

If x is neither directly in scope, kept alive by closure nor global, then it will be inaccessible and/or lost to garbage collection.

If scope issues make things difficult, you could alternatively move myDiv inside a hidden DOM element (eg another div reserved for this purpose) from which it can be recovered at any point in the code regardless of scope (the DOM is effectivey global). The move in would typically be performed with .append() while the move back out would be performed with .append(), .after() or .prepend().

Airshow

Vishal,

As it says in the jQuery API, jQuery.remove() returns jQuery , so you can do something like this:

var x = $('#myDiv').remove();
//.......
$('#myElement').append(x);//or .after() or .prepend() depending on how you need to insert x back into the DOM. Of course, like any javascript member, x must be in scope, or formally passed to a function that operates on it.

If x is neither directly in scope, kept alive by closure nor global, then it will be inaccessible and/or lost to garbage collection.

If scope issues make things difficult, you could alternatively move myDiv inside a hidden DOM element (eg another div reserved for this purpose) from which it can be recovered at any point in the code regardless of scope (the DOM is effectivey global). The move in would typically be performed with .append() while the move back out would be performed with .append(), .after() or .prepend().

Airshow

thanks, Airshow . I used the the .append() and it worked :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.