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 >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
CodePudding user response:
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 >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
CodePudding user response:
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 >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<div >
<div >
<h3>submit</h3>
</div>
</div>
<button id="replace">Replace</button>