I am struggling to replace h2
using JS. I keep getting Uncaught TypeError: Failed to execute 'replaceChild' on 'Node': parameter 2 is not of type 'Node'.
I tried converting it:
let prevHeading = document.getElementsByClassName('my-title');
prevHeading = Array.from(prevHeading);
didn't work.
<body>
<div id="outer-box" style="margin: 20px;">
<h2 class="my-title">OLD TITLE</h2>
<div class="inner-box">
<ul class="main-list">
<li class="list-item">List Item 1</li>
<li class="list-item">List Item 2</li>
<li class="list-item">List Item 3</li>
<li class="list-item">List Item 4</li>
<li class="list-item">List Item 5</li>
</ul>
</div>
</div>
</body>
const newHeading = document.createElement('h2');
newHeading.className = 'my-title';
newHeading.appendChild(document.createTextNode('NEW TITLE'));
const prevHeading = document.getElementsByClassName('my-title');
const outerBox = document.querySelector('#outer-box');
outerBox.replaceChild(newHeading, prevHeading);
I could just use prevHeading[0]
but I just wanna know why it isn't working.
It also works with:
const prevHeading = document.querySelector('.my-title');
CodePudding user response:
In my opinion, you complicated the things.
You can just use querySelector and InnerHtml to replace the title :
var title = document.querySelector(".my-title") ;
title.innerHTML = "NEW TITLE" ;
CodePudding user response:
Your code works as posted so long as you access the individual node from the HTMLCollection
returned by getElementsByClassName()
.
// This works to convert the HTMLCollection to an Array
let prevHeading_example = document.getElementsByClassName('my-title');
prevHeading_example = Array.from(prevHeading_example);
console.log('prevHeading array: ', prevHeading_example);
// This whole block works so long as you access the individual node 'prevHeading[0]'
const newHeading = document.createElement('h2');
newHeading.className = 'my-title';
newHeading.appendChild(document.createTextNode('NEW TITLE'));
const prevHeading = document.getElementsByClassName('my-title');
const outerBox = document.querySelector('#outer-box');
outerBox.replaceChild(newHeading, prevHeading[0]); // <-- access node at index 0
<body>
<div id="outer-box" style="margin: 20px;">
<h2 class="my-title">OLD TITLE</h2>
<div class="inner-box">
<ul class="main-list">
<li class="list-item">List Item 1</li>
<li class="list-item">List Item 2</li>
<li class="list-item">List Item 3</li>
<li class="list-item">List Item 4</li>
<li class="list-item">List Item 5</li>
</ul>
</div>
</div>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>