Reputation: 1122
Assume I have a DOM tree represented by this html.
<div id="root">
<div>
<p>hoge</p>
<span>fuga</span>
</div>
<div>
<span>piyo</span>
<div>
<span>foobar</span>
</div>
</div>
</div>
If I want to replace all the <span>
s by <button>
, how could I achieve it?
const replaceElements = () => {
const page = document.getElementById("root")
const elements = document.getElementsByTagName('span');
elements.forEach(item => ???)
}
Upvotes: 0
Views: 71
Reputation: 924
It keeps getting the first span
and converting it to a button until there are no more span
s by replacing the element with button tags around the span's innerHTML. Check out the snippet. (tested in Chrome 76)
const replaceElements = () => {
const elements = document.getElementsByTagName('span');
while (elements.length > 0) {
const item = elements[0];
item.outerHTML = '<button>' + item.innerHTML + '</button>';
}
}
const replaceElements = () => {
const elements = document.getElementsByTagName('span');
while (elements.length > 0) {
const item = elements[0];
item.outerHTML = '<button>' + item.innerHTML + '</button>';
}
}
replaceElements();
<div id="root">
<div>
<p>hoge</p>
<span>fuga</span>
</div>
<div>
<span>piyo</span>
<div>
<span>foobar</span>
</div>
</div>
</div>
Upvotes: 1
Reputation: 153
The way that you have it set up you will need to assign the innerHTML of the spans into new button elements for each span found. Try this:
const replaceElements = () =>{
//get all span elements
var spans = document.querySelectorAll("span");
// loop over all of them
for(let i=0; i<spans.length;i++){
// create the new btn and get the parent
var newBtn = document.createElement("button"),
parent = spans[i].parentNode;
// set innerhtml of btn
newBtn.innerHTML = spans[i].innerHTML;
// replace the node in the parent container
parent.replaceChild(newBtn,spans[i]);
}
}
Upvotes: 1