JQuery: an elegant way to replace a set of elements with another set?

I have a bunch of DOM, sort of

<div> <div class="stuff"/> <div class="stuff"/> <div class="stuff"/> </div> 

and I want to replace it with a new set of materials

 <div> <div class="stuff"/> <p class="stuff"/> <ul class="stuff"/> <a class="stuff"/> </div> 

What will be selected through Ajax. My question is: what is the best way to do this?

$.replaceWith doesnโ€™t quite do what I want, because in the end I get several copies of the new stuff .

I can guarantee that all stuff will be in one adjacent block, and therefore I could presumably put in some placeholder after the last element (or before the first element) of the old stuff , delete the old stuff and replace the placeholder with the new stuff .

However, it seems pretty cool and inelegant. Is there any smart way by deleting all the old stuff and inserting one copy of the new stuff , all at a time?

EDIT: I would also like to do this without using any div containers. Using divs containers will work in the above case, but in some cases will not work, for example, when stuff is inside the <table> :

 <table> <head/> <body> <tr/> <tr class="stuff"/> <tr class="stuff"/> <tr class="stuff"/> <tr/> </body> </table> 

If I want to replace the lines with the label stuff with a different set of lines, maybe more, maybe less, I canโ€™t put them well in the container without breaking the HTML, since <body> can only contain <tr> (IIRC).

+7
source share
3 answers
 $('#outerdiv').empty().append(newContent); 

Unlike .html() , this will work whether the newContent HTML string or an existing DOM structure.

If there are several elements that need to be replaced, but where you need to save your brothers and sisters, you can do this:

 $('.stuff').first().before(newContent).end().remove(); 

i.e. take the first .stuff element, add new content in front of it and delete all .stuff elements.

+11
source

Yes: $('#tagetDiv').html(newContent)

+3
source

One way to do this would be with wrapAll :

 $('.stuff').wrapAll('<div/>').parent().replaceWith('<div class="stuff"/>'); 

I'm not sure if this passes the โ€œelegantโ€ test, but it works regardless of whether there is any other content in the containing element.

With that said, however, this seems like a very complicated solution to a simple problem. A simple solution would be to wrap your elements in a containing element; this should not be a problem if, as you say, you can guarantee that they will always be together.

+2
source

All Articles