Reputation: 1058
Suppose I have a single HTML element that I want to be replaced in the body
i.e. this is the body
<p> some random element </p>
<a href="#" id="dfd32"> some text</a> // this element to replace
<h1> some random element </h1>
Now I want this element to get replaced by an array of elements
[
<a href="#" id="dsd32dsd"> 23dfsome text12</a>,
<a href="#" id="dfwedwew"> sdfsome text23</a>,
<a href="#" id="dssfd"> somdfse text2</a>
]
the final body after getting replaced will be
<p> some random element </p>
<a href="#" id="dsd32dsd"> 23dfsome text12</a>
<a href="#" id="dfwedwew"> sdfsome text23</a>
<a href="#" id="dssfd"> somdfse text2</a>
<h1> some random element </h1>
How to do that ? I tried with replaceWith
but not able to do it.
Upvotes: 1
Views: 1492
Reputation: 43934
You can't insert a NodeList directly, since replaceWith
does not accepts an array as parameter.
Luckily there are some ways around this
If we use the spread operator (...
) on our array with nodes, replaceWith()
will insert the elements as expected:
// Array to replace
const ar = [];
for (var i = 1; i <= 3; i++) {
let tmp = document.createElement('a');
tmp.innerHTML = 'Link #' + i;
ar.push(tmp);
}
// Get element to replace
const el = document.getElementById('dfd32');
// Insert the array nodes
el.replaceWith(...ar);
<p> some random element </p>
<a href="#" id="dfd32"> some text</a>
<h1> some random element </h1>
jQuerys version of replaceWith
does work with a regular array containing DOM elements:
// Array to replace
const ar = [ $('<a>Link #1</a>'), $('<a>Link #2</a>'), $('<a>Link #3</a>') ];
// Get and replace
$('#dfd32').replaceWith(ar);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> some random element </p>
<div href="#" id="dfd32"> some text</div>
<h1> some random element </h1>
Upvotes: 4