'replacing tag with another tag targeting class
Trying to change the h3
tag to a <button>
tag targeting via .container
and .button-1
class using JavaScript. Unfortunately, it only targets the first h3
var allWindow = document.querySelector('.container .button-1 h3');
allWindow.outerHTML = '<button>submit</button>';
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
Solution 1:[1]
Your problem is you're using querySelector
which is always referred to the first-found element. I'd suggest that you should change it to querySelectorAll
(get all elements) and use a loop to update all your elements
var allWindows = document.querySelectorAll('.container .button-1 h3');
for(let element of allWindows) {
element.outerHTML = '<button>submit</button>';
}
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
Solution 2:[2]
const replaceAll = () => {
const elems = document.querySelectorAll('.container > .button-1 > h3');
[...elems].forEach((elem) => {
const button = document.createElement('button');
button.textContent = 'submit';
elem.replaceWith(button);
});
};
document.querySelector('#replace').addEventListener('click', replaceAll);
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<div class="container">
<div class="button-1">
<h3>submit</h3>
</div>
</div>
<button id="replace">Replace</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nick Vu |
Solution 2 | mstephen19 |