0

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>
1
  • 1
    That's because you used insertAdjacentHTML, but title is not a string value containing HTML code, it is an HTMLElementObject. Use appendChild instead. Commented Jun 17, 2022 at 11:47

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.