Home > Software engineering >  How to insert html elements
How to insert html elements

Time:06-17

I'm trying to insert the whole element into the container element however It throws some object into the DOM

JS:

const CONTAINER = document.getElementById('container');
let title = document.querySelector('h1').cloneNode(true);
CONTAINER.insertAdjacentHTML('beforeend', title);

HTML:

<div  id="container"></div>
<h1>Test</h1>

CodePudding user response:

title it is an HTMLElementObject. Use appendChild instead.

const CONTAINER = document.getElementById('container');
let title = document.querySelector('h1').cloneNode(true);
CONTAINER.appendChild(title);
<div  id="container"></div>
<h1>Test</h1>

CodePudding user response:

Or, as a one-liner:

document.getElementById('container').insertAdjacentHTML('beforeend', document.querySelector('h1').outerHTML);
<div  id="container">This is the target container</div>
<p>Some padding text</p>
<h1>Test</h1>

  • Related