<body>
<input type="text" id="txtElement">
<button id="btnKnop1">Vervang tekst</button>
<div id="divResult">
<p class="special">Alinea 1</p>
<p class="special">Alinea 2</p>
<p class="special">Alinea 3</p>
<p>ALinea 4</p>
<p>Alinea 5</p>
</div>
<script type="text/javascript">
window.addEventListener('load', () => {
document.getElementById('btnKnop1').addEventListener('click', () => {
let OldElement = document.getElementsByClassName('special')
let newElement = document.createElement('p');
let node = document.getElementById('txtElement').value;
let newNode = document.createTextNode(node)
newElement.appendChild(newNode)
console.log(newElement)
document.getElementById('divResult').replaceChild(newElement, OldElement)
})
})
</script>
</body>
I want to change the paragraph with the text from the input field on a button click.
Same goes for all the paragraphs.
I tried above but it didn’t work.
2
Answers
There are multiple paragraphs with the same class, so you’ll have to do this
The
document.getElementsByClassName('special')
method returns an array of HTML elements but thereplaceChild(newElement, OldElement)
method expects a single element see https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChildIf you want to replace all of the
class="special"
elements you need to iterate over theOldElement
array like this:Note: I am using the
newElement.cloneNode(true)
method because if the new node is already present somewhere else in the DOM, it is first removed from that position.