DEV Community

Cover image for JavaScript DOM Manipulation Cheatsheet✨
Tabassum Khanum
Tabassum Khanum

Posted on

JavaScript DOM Manipulation Cheatsheet✨

Hey Coders!☃

In this article, we are going to learn about one of the most important topic- DOM Manipulation that newbie JavaScript learners may find overwhelming at the start. It's an important topic in web development because the DOM serves as the initial use of JavaScript in the browser. I’ve tried to put together a super helpful cheat sheet to give you a complete overview of the DOM manipulation methods. So if you are ready, let's jump in!

gif

Hello DOM!

One of the most unique and useful abilities of Javascript is to manipulate the DOM. So what exactly is DOM and why is everyone in the industry throwing its term everywhere?

Definition in plain English -

"The DOM(or Document Object Model) is a tree-like representation of the web page that gets loaded into the browser.
It represents the web page using a‌‌ series of objects. The main object is the document object, which in turn houses other objects which also house their own objects, and so on."

The DOM is a tree-like representation of the contents of a webpage - a tree of “nodes” with different relationships depending on how they’re arranged in the HTML document.

It has properties and methods which you can use to get information about the document using a rule known as dot notation.

DOM Tree Analogy

Image description

One of the main reasons for developing the DOM is to maintain a standard programming interface for HTML. Setting and maintaining this standard enables programmers to create or navigate these types of documents and modify their elements predictably, using any type of language or development environment.

The individual elements in an HTML document are called "nodes" in DOM terms. The relationship between elements in a document is "tree-like", meaning that like a tree has a main trunk, from which stem certain main branches, which in turn branch off into finer branches and so on, so does an HTML document contain certain "key" elements, like the <head> and <body>, which in turn contain other elements, like <div>'s, <p>'s and others.



<div id="container">
  <div class="display"></div>
  <div class="controls"></div>
</div>



Enter fullscreen mode Exit fullscreen mode

In the above example, the <div class="display"></div> is a “child” of <div id="container"></div> and a sibling to <div class="controls"></div>. Think of it like a family tree. <div id="container"></div> is a parent, with its children on the next level, each on their own “branch”.

Uses of DOM

  • first of all, locating elements in the document by their ID, class, tag name (div, p, etc.), and other characteristics
  • adding, removing, or modifying the HTML elements themselves
  • modifying any attribute of an HTML element, such as their class, style attributes, and others

Selecting Element in the DOM

JavaScript provides six methods to select an element from the document.

getElementById

– search element by element_id

The Document method getElementById() returns an Element an object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.



function changeColor(newColor) {
  const elem = document.getElementById("para");
  elem.style.color = newColor;
}



Enter fullscreen mode Exit fullscreen mode

getElementsByTagName

– search element by tag name (e.g., span, div)

The Element.getElementsByTagName() method turns a live HTMLCollection of elements with the given tag name.

When called on an HTML element in an HTML document, getElementsByTagName lower-case the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS(), which preserves the capitalization of the tag name.




const table = document.getElementById("forecast-table");
const cells = table.getElementsByTagName("td");



Enter fullscreen mode Exit fullscreen mode

getElementsByClassName

– search element by class name

The Element method getElementsByClassName() returns a live HTMLCollection which contains every descendant element which has the specified class name or names.




element.getElementsByClassName("test");



Enter fullscreen mode Exit fullscreen mode

getElementsByName

– search element by the name attribute

The getElementsByName() method of the Document object returns a NodeList Collection of elements with a given name attribute in the document.



const up_names = document.getElementsByName("up");



Enter fullscreen mode Exit fullscreen mode

querySelector

– returns the first element that matches the specified selector

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.




const el = document.querySelector(".myclass");



Enter fullscreen mode Exit fullscreen mode

querySelectorAll

– returns elements that match the specified selector

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.




const container = document.querySelector("#test");
const matches = container.querySelectorAll("div.highlighted > p");



Enter fullscreen mode Exit fullscreen mode

Styling an Element

You can directly change each CSS property of an element by using the style property, which references the element's inline styles.

For example, you can change an element color using:




element.style.color = '#fff'


Enter fullscreen mode Exit fullscreen mode

You can alter the border:



element.style.border = '1px solid black'



Enter fullscreen mode Exit fullscreen mode

Creating Elements

The Document object provides a method createElement() to create an element and appendChild() method to add it to the HTML DOM.

The document.createElement() method creates the HTML element specified by tagName.



createElement(tagName)
createElement(tagName, options)

const newDiv = document.createElement("div");


Enter fullscreen mode Exit fullscreen mode

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.



// Create a new paragraph element, and append it to the end of the document body
const p = document.createElement("p");
document.body.appendChild(p);



Enter fullscreen mode Exit fullscreen mode

Modify Text

The easiest way to modify the content of an HTML element is by using the innerHTML property.



const element = document.getElementById("id01");

element.innerHTML = "New Heading";



Enter fullscreen mode Exit fullscreen mode

Modifying Element Classes and IDs

The id property sets or returns the value of an element's id attribute.



document.getElementById("demo").id = "newid";



Enter fullscreen mode Exit fullscreen mode

The className is used as a selector in HTML which helps to give some value to the element attributes. The document.getElementById() method is used to return the element in the document with the “id” attribute and the “className” attribute can be used to change/append the class of the element.



document.getElementById('myElement').className = "myclass";



Enter fullscreen mode Exit fullscreen mode

Remove an Element

ES6 provides an easier, simpler way to achieve the same tax: remove(). Call the remove() method on the element you want to remove.



var elem = document.querySelector('#some-element');
elem.remove();



Enter fullscreen mode Exit fullscreen mode

Traversing the DOM

Read this article to get to know about DOM traversing - https://medium.com/codex/how-to-traverse-the-dom-in-javascript-7fece4a7751c

Event Listeners

The JavaScript addEventListener() method allows you to set up functions to be called when a specified event happens, such as when a user clicks a button.




target.addEventListener(event, function, useCapture)


Enter fullscreen mode Exit fullscreen mode
  • target: the HTML element you wish to add your event handler to. This element exists as part of the Document Object Model (DOM).
  • event: a string that specifies the name of the event. We already mentioned load and click events.
  • function: specifies the function to run when the event is detected. This is the magic that can allow your web pages to change dynamically.
  • useCapture: an optional Boolean value (true or false) that specifies whether the event should be executed in the capturing or bubbling phase.


button.addEventListener('click', (e)=>{
console.log(e.target.id)
})

Enter fullscreen mode Exit fullscreen mode




Removing Event Handlers

If for some reason you no longer want an event handler to activate, here's how to remove it:



target.removeEventListener(event, function, useCapture);

Enter fullscreen mode Exit fullscreen mode




Wrapping Up

I hope you've learned at least a couple of things from this article, thank you for reading till the end! And let me know if I should change or add anything to this article.
For daily web development threads, updates and content follow me on Twitter.
Happy Coding🌼

gif

Latest comments (2)

Collapse
 
john_ladykiller_32194ef7e profile image
John Ladykiller

Great share!

Collapse
 
himanshudevgupta profile image
Himanshu Gupta

Nice article