DEV Community

Cover image for The Ultimate Guide To JavaScript Dom Manipulation With Practice Project
Fahim Zada
Fahim Zada

Posted on

The Ultimate Guide To JavaScript Dom Manipulation With Practice Project

Hi there,
In website development, DOM stands for Document Object Model. DOM manipulation is when you use JavaScript to add, remove, and modify elements of a website. And in this tutorial, you'll learn how to do it. I'll include a GitHub link to a practice project in the end which you should check out.
We will not be covering events, event handlers, and different ways of accessing and manipulating elements. But the recommended and easy way.

Accessing Dom Elements

Same as you select elements through CSS.

// Returns the first element within the document that matches the specified group of selector/selectors. 
//Now you have also access to the element attributes, element.href etc and you can directly change any property element.href = "https://newlink.com"
const element = document.querySelector('.someclass')
// Returns a list of the elements within the document using depth-first pre-order traversal of the document's node. That match the specified group of selector/selectors.
const eleList = document.querySelectorAll('.someclass')
// Getting child nodes
const getIt = document.querySelector('.someclass')
const children = getIt.childNodes
// Getting parent node
const parent = children.parentNode
//A few others you can use
//element.previousSibling
//element.nextSibling
//element.firstChild
//element.lastChild
Enter fullscreen mode Exit fullscreen mode

Creating New DOM Elements

//create h1 element
const heading = document.createElement('h1');
// create a text node for the element
const headingText= document.createTextNode('This is the h1 heading!');
// Attach the text node to the element
heading.appendChild(headingText);
//Append the element to the body or to a specific element
document.body.appendChild(heading)
element.appendChild(heading)
Enter fullscreen mode Exit fullscreen mode

Selecting the element, Adding the content, Replacing and removing elements

//Select the element
const element = document.querySelector('.someclass')
//Get the inner text , innerText or just using the text
const insideText = element.innerText
//Adding more content to element
element.innerText = insideText + "the new value"
//Replacing the value
element.innerText = "New Value"
//Use innerHTML if you want to add HTML along with it
element.innerHTML = "New Heading Value <a href="https://dev.to/itsfz1">Developer</a>"
//Let's remove this element from the dom tree
element.remove()
Enter fullscreen mode Exit fullscreen mode

Inserting HTML at different locations

const element = document.querySelector('.someclass')
// beforebegin - The HTML would be placed immediately before the element, as a sibling.
// afterbegin - The HTML would be placed inside the element, before its first child.
// beforeend - The HTML would be placed inside the element, after its last child.
// afterend - The HTML would be placed immediately after the element, as a sibling.
element.insertAdjacentHTML("afterbegin
", "<div><p>New Grid Item</p></div>");
Enter fullscreen mode Exit fullscreen mode

Add, Remove, Toggle, Check Classes

const element = document.querySelector('.someclass')
// Will remove unwanted if it is a class of element
element.classList.remove("unwanted");
//Will add the class 'anotherClass' if one does not already exist
element.classList.add("anotherclass");
// Add or remove multiple classes
element.classList.add("class1", "class2");
element.classList.remove("c1", "c2");
//If "visible" class is set remove it, otherwise add it
element.classList.toggle("visible");
// will return true if it has class of 'exist' or false if it does not
const flag = element.classList.contains("exist");
flag ? "Yes this class exist" : "Not exist"
Enter fullscreen mode Exit fullscreen mode

Getting, Adding, and removing attributes

const element = document.querySelector('.someclass')
//will return the link
element.getAttribute("href")
//will set class="awsome"
element.setAttribute("class", "awsome")
//Will remove the attribute from element
element.removeAttribute("class")
//Check for attribute existance, it returns a boolean
if (element.hasAttribute("target")) {
    element.setAttribute("style", "color: green; text-decoration: none;");
  }
Enter fullscreen mode Exit fullscreen mode

Here is the link for the practice project.

Bonus

You can assign multiple attributes without using multiple setAttribute functions in one go like this:

const elementInput = document.createElement("input")
 Object.assign(elementInput , {
        className: "textField",
        id: "address",
        name: "address",
        type: "text",
        placeholder: "",
        value: ""
    })
document.body.appendChild(elementInput )
Enter fullscreen mode Exit fullscreen mode

The difference between "innerText" and "textContent" is that innerText returns only visible text without spacing while textContent returns visible and non-visible text including a script with spacing.
Thanks for reading!.

Top comments (0)