Fiddle: https://jsfiddle.net/1b81gv7q/
Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it.
Imagine this scenario: there's a container with content that needs to be dynamically replaced.
If I wanted to replace everything within the template
DOM node, while keeping the static-container
intact, how would I achieve that? It's important to note that simply targeting h1
and p
won't cut it. The entire contents of the template
container need to be swapped, except for the static-container
, which should stay in place as the last child of template
.
I'm not looking for solutions that rely on React, Vue, Angular, or any other framework. Strictly interested in pure JavaScript or jQuery solutions.
$('button').click(function() {
let newTemplate = $('.new-template').html();
$('.template').html(newTemplate);
});
.new-template {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="template">
<h1>header #1</h1>
<p>some text for #1</p>
<div class="static-container">
<div>
<p>a b c 1 2 3</p>
<p>d e f 4 5 6</p>
</div>
</div>
</div>
</div>
<button>change template</button>
<div class="new-template">
<h1>header #2</h1>
<p>some text for #2</p>
<div class="static-container"></div>
</div>