In this post we're going to learn how to create elements, add a node to the list of children of the parent node get and set the content of nodes and elements
createElement
Using the document.createElement()
allows you to create an HTML element. This method accepts an HTML tag name into the as argument and then returns a new Node of the Element type.
const h1 = document.createElement('h1');
console.log(h1);
In the example above, we created an <h1>
element which is not visible yet on the screen.
innerHTML
You can obtain or modify the HTML markup that is present in an element by using its innerHTML
property.
const h1 = document.createElement('h1');
h1.innerHTML = "Title";
console.log(h1);
<h2 id="heading">This is an h2</h2>
const h2 = document.getElementById('heading');
console.log(h2.innerHTML);
textContent
Using the textContent
property will allow you to obtain a node's and its descendants' text content.
<ul id="menu">
<li>Lorem, ipsum.</li>
<li>Lorem, ipsum dolor.</li>
<li>Lorem, ipsum.</li>
</ul>
const menu = document.getElementById('menu');
console.log(menu.textContent);
You can also set the text content of a node, meaning if we take our JavaScript code and modify it like so:
const menu = document.getElementById('menu');
menu.textContent ='This is an example';
console.log(menu.textContent);
the output will change from:
to:
appendChild
By using the appendChild() method, you can add a node to the end of a parent node's list of children.
<ul id="menu">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
const menu = document.getElementById("menu");
const li = document.createElement("li");
li.innerHTML ="Last Item";
menu.appendChild(li);
Before appending:
After appending the list item
Top comments (0)