Vince
Vince

Reputation: 869

How to insert html elements

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 class="container" id="container"></div>
<h1>Test</h1>

Upvotes: 0

Views: 64

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Or, as a one-liner:

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

Upvotes: 2

X3R0
X3R0

Reputation: 6324

title it is an HTMLElementObject. Use appendChild instead.

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

Upvotes: 1

Related Questions