Oftentimes, we want to append HTML content into a container element.
Sometimes, we want to do this without setting the innerHTML
property of the container element to do so.
In this article, we’ll look at how to append HTML to a container element without setting the innerHTML
property of the container element with JavaScript.
Use document.createElement and appendChild
One way to add child elements to a container element without setting the innerHTML
property is to use the document.createElement
method to create the element.
Then we can call appendChild
to append the element.
For instance, if we have the following HTML:
<div>
</div>
Then we can write:
const element = document.querySelector('div')
const e = document.createElement('div');
const htmldata = 'hello world'
e.innerHTML = htmldata;
while (e.firstChild) {
element.appendChild(e.firstChild);
}
We get the div that we added with querySelector
.
Then we call document.createElement
to create another div that we insert into the parent div as a child element.
We set e.innerHTML
‘s value of the newly created element to add some content into it.
And then we call element.appendChild
to add the child element into the div we initially added.
Now we should see ‘hello world’ on the screen.
Use the insertAdjacentHTML Method
Another way to insert a child element into a container element as a child element is to use the insertAdjacentHTML
method.
If we have the following HTML:
<div>
</div>
Then we can use it by writing:
const element = document.querySelector('div')
element.insertAdjacentHTML('beforeend', '<div>hello world</div>');
We get the div with querySelector
.
Then we call insertAdjacentHTML
with 'beforeend'
and the HTML we want to insert into the div as arguments.
Now we should see the same result as the previous example.
Conclusion
We can append HTML to a container element without setting innerHTML with JavaScript by using various methods available in DOM element objects.