jQuery or native JS replacing entire element (div) including its id, classes and data

Viewed 43

Let's say there are several similar elements like:

<div id="element_01" class="element" data-id="01" data-color="blue">
    Some content
</div>

<div id="element_02" class="element" data-id="02" data-color="yellow">
    Some content
</div>

<div id="element_03" class="element" data-id="03" data-color="green">
    Some content
</div>

With an AJAX call I have to get a new entire element, including all attributes of it and replace one of the elements above with it. The loaded element could look like this:

<div id="element_02" class="element active" data-id="02" data-color="red">
    Some NEW content
</div>

As you can see, it is actually the same as element_02 in the original group, but with another content, an additional class and with a different data-color value. The desired result should look like this:

<div id="element_01" class="element" data-id="01" data-color="blue">
    Some content
</div>

<div id="element_02" class="element active" data-id="02" data-color="red">
    Some NEW content
</div>

<div id="element_03" class="element" data-id="03" data-color="green">
    Some content
</div>

I know how to load the contents of an element into another element, which would be:

$('#element_02').load(url+' > *');

But that loads, as mentioned, only the contents into the element and leaves the classes and the data attributes alone.

Of course, I could manually just add the new class to the element and change the data value manually after the load with a function, like so:

$('#element_02').load(url+' > *', function(){

   $('#element_02').addClass('active');
   $('#element_02').data('color', 'red');

});

But I was wondering if there is a more universal approach which takes care of all the parent attributes without manually having to add or change them.

My idea would be like.

  • Create temporary div
  • load entire element into temporary div
  • copy contents of temporary div and insertAfter target element
  • remove temporary div
  • remove the original/target div

Would something like that work without big hickups and glitches while loading?

Maybe someone has a solution for this. Thanks.

1 Answers

I have now indeed managed to solve it myself with the suggested idea. Probably not perfect, but works.

function ReplaceElementCompletely(id) { 
    
    $('.element[data-id="'+id+'"]').addClass('remove_this');
    
    $('<div class="temporary"></div>').insertAfter('.element[data-id="'+id+'"]');

    $('div.temporary').load(url+' .element[data-id="'+id+'"]', function(){

        $('.temporary > .element').insertBefore('.temporary');
        $('.temporary').remove();
        $('.remove_this').remove();

    });
    
}   
    
ReplaceElementCompletely('02');
Related