DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for DOM Manipulation: part II

DOM Manipulation: part II

In a previous article, we talked about DOM selectors, styling, text modifiers and events. Let's focus now on the following DOM concepts:

  • DOM create & remove elements
  • DOM classes
  • DOM attributes

DOM create & remove elements

If we want to add certain elements to our app or website with JavaScript, we can use the following methods:

document.createElement(name of the tag) β†’ creates an HTML element:

createElement method

document.appendChild() or element.append() β†’ adds an HTML element where we want:

appendChild method

document.insertAdjacentElement(position, element) β†’ adds an HTML element before or after another element, in the position we indicate (afterbegin or beforeend) and using template literals. It is commonly used with lists:

insertAdjacentElement method

element.remove() β†’ removes an element from the DOM:

DOM classes

JavaScript also allows us to play with classes to show or hide an element in the DOM. The basic methods to add and remove a class or check if an element has a class are:

  • element.classList.add(β€œclassName”)
  • element.classList.remove(β€œclassName”)
  • element.classList.contains(β€œclassName”) β†’ returns a boolean (true or false) whether the class exists or not.

Let's have a look at an easy example and see how to play with classes with JS:

We create the class in CSS with the styling we would like to apply to an HTML element and afterwards we simply add the class to the desired element with element.classList.add(β€œclassName”)

Another example to reveal and hide content using classes:

Very similar to the previous concepts is element.classList.toggle("className"), which adds or removes a class depending on whether the class already exists or not. Have a look at the following simple example:

We can also replace a class name with a new one with:

remove classList

DOM attributes

HTML elements can have attributes like class, id or disabled. In order to manipulate them we can use the following methods:

element.getAttribute(key) β†’ takes an attribute's value:

getAttribute example

element.removeAttribute(key) β†’ removes an attribute's value. According to the previous example:

removeAttribute example

element.setAttribute(key, value) β†’ adds an attribute and gives it a name or value:

setAttribute example

element.hasAttribute(key) β†’ checks if an attribute exists and returns a boolean:

hasAttribute example

Put in practise all DOM concepts that you have learnt with the following fun projects from Freecodecamp!

DOM challenges

Find all challenges here.

Top comments (0)

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.