DEV Community

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

Posted on • Edited on

JavaScript Tutorial Series: Manipulating elements part 2.

In this post we're going to talk about four more methods that will help you manipulate the DOM.
There's a huge number of methods/properties that helps you manipulate the DOM. Not all of them are mentioned, but only the important or commonly used ones.

prepend

The prepend() method places a group of Node objects or DOMString objects before a parent node's first child.

<ul id="list">
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

HTML list

const list = document.getElementById("list");

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

item.textContent = "fourth item";

list.prepend(item);
Enter fullscreen mode Exit fullscreen mode

prepend method

As you can see, the element we created using JavaScript is placed before the first child of that list.

append

The append() method inserts a number of Node objects or DOMString objects after a parent node's final child,

<ul id="list">
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

HTML list

const list = document.getElementById("list");

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

item.textContent = "fourth item";

list.append(item);
Enter fullscreen mode Exit fullscreen mode

append method

replaceChild

The replaceChild() method is used to replace a parent node's child.

Syntax

parentNode.replaceChild(newChild, oldChild);

Enter fullscreen mode Exit fullscreen mode

Using the example above we're going to replace the first item of the list.

<ul id="list">
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

HTML list

const list = document.getElementById("list");

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

item.textContent = "new child item";

list.replaceChild(item, list.firstElementChild);
Enter fullscreen mode Exit fullscreen mode

replaceChild method

removeChild

The removeChild() method is used to remove a child element from a node.

Syntax

parentNode.removeChild(childNode);
Enter fullscreen mode Exit fullscreen mode

Using the same example, we're going to remove the first element in the unordered list.

<ul id="list">
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

HTML list

const list = document.getElementById("list");
list.removeChild(list.firstElementChild);
Enter fullscreen mode Exit fullscreen mode

removeChild method

Top comments (1)

Collapse
 
changintimes profile image
Larry

I enjoy these Javascript articles. Thanks.