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!
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
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>
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_idThe
Document
methodgetElementById()
returns anElement
an object representing the element whoseid
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; }
getElementsByTagName
– search element by tag name (e.g., span, div)The
Element.getElementsByTagName()
method turns a liveHTMLCollection
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, useElement.getElementsByTagNameNS()
, which preserves the capitalization of the tag name.const table = document.getElementById("forecast-table"); const cells = table.getElementsByTagName("td");
getElementsByClassName
– search element by class nameThe
Element
methodgetElementsByClassName()
returns a liveHTMLCollection
which contains every descendant element which has the specified class name or names.element.getElementsByClassName("test");
getElementsByName
– search element by the name attributeThe
getElementsByName()
method of theDocument
object returns aNodeList
Collection of elements with a givenname
attribute in the document.const up_names = document.getElementsByName("up");
querySelector
– returns the first element that matches the specified selectorThe
Document
methodquerySelector()
returns the firstElement
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");
querySelectorAll
– returns elements that match the specified selectorThe
Document
methodquerySelectorAll()
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");
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'
You can alter the border:
element.style.border = '1px solid black'
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");
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);
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";
Modifying Element Classes and IDs
The id
property sets or returns the value of an element's id attribute.
document.getElementById("demo").id = "newid";
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";
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();
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)
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
andclick
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. I
button.addEventListener('click', (e)=>{
console.log(e.target.id)
})
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);
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🌼