DEV Community

Cover image for JavaScript Tutorial Series: Manipulating elements part 1
The daily developer
The daily developer

Posted on • Updated on

JavaScript Tutorial Series: Manipulating elements part 1

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);
Enter fullscreen mode Exit fullscreen mode

create element method
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);
Enter fullscreen mode Exit fullscreen mode

Inner HTML method

<h2 id="heading">This is an h2</h2>
Enter fullscreen mode Exit fullscreen mode
const h2 = document.getElementById('heading');
console.log(h2.innerHTML);
Enter fullscreen mode Exit fullscreen mode

inner HTML method

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>
Enter fullscreen mode Exit fullscreen mode
const menu = document.getElementById('menu');

console.log(menu.textContent);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

the output will change from:

text Content method

to:

TextContent method

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>
Enter fullscreen mode Exit fullscreen mode
const menu = document.getElementById("menu");

const li = document.createElement("li");

li.innerHTML ="Last Item";

menu.appendChild(li);
Enter fullscreen mode Exit fullscreen mode

Before appending:

append child

After appending the list item

appendChild method

Top comments (0)