Sunday, December 4, 2022
HomeJavaScript10 Must Know JavaScript DOM Methods

10 Must Know JavaScript DOM Methods

JavaScript is one of the most popular choices for developers all around the world in order to create interactive websites or web applications. If you want to develop an interactive website with a unique user experience you must have knowledge of JavaScript DOM Methods. With the help of JavaScript DOM Methods, you create, select and update the content of a given HTML.

In this article, we will study different important JavaScript DOM Methods with examples you can use during development to make your web application/ website interactive and valuable.  

10 Must-Know JavaScript DOM Methods

Document.querySelector()

This method returns the first element from the document that matches the given selector or selectors and if there is no element present then it returns null.

Note:- If you want to select all the elements that match with the given selector then use Document.querySelectorAll() method.

Example

<button class='btn'>1st button</button>
<button class='btn'>2nd button</button>
<button class='btn'>3rd button</button>
<button class='btn'>4th button</button>

<script>

let element = document.querySelector('.btn');

console.log(element) // <button class='btn'>1st button</button>

let allElement = document.querySelectorAll('.btn');

console.log(allElement)

// [ <button class='btn'>1st button</button>
//   <button class='btn'>2nd button</button>
//   <button class='btn'>3rd button</button>
//   <button class='btn'>4th button</button> ]

</script>

Also read, Difference between var vs let vs const in JavaScript | TDZ

Document.getElementsByClassName()

This method returns array-like an object of all the elements that contain the same given class.

Example

<button class='btn'>1st button</button>
<button class='btn'>2nd button</button>
<button class='btn'>3rd button</button>
<button class='btn'>4th button</button>

<script>
let element = document.getElementsByClassName('btn')

console.log(element)
// [
// <button class='btn'>1st button</button>
// <button class='btn'>2nd button</button>
// <button class='btn'>3rd button</button>
// <button class='btn'>4th button</button>
// ]
</script>

Note:- This method return live HTMLCollection. Any changes in the DOM will be reflected in the array as the changes occur.

You can also call this method on another element and returns all the children of that element with the given class name. This is because it searches the whole document, including the root node.

Example

<div class='set-btn'>
  <button class='btn'>1st button</button>
  <button class='btn'>2nd button</button>
  <button class='blue-btn'>3rd button</button>
  <button class='btn'>4th button</button>
</div>

<script>
let element = document.querySelector('.set-btn')

let children = element.getElementsByClassName('btn')

console.log(children)

// [<button class='btn'>1st button</button>
//  <button class='btn'>2nd button</button>
//  <button class='btn'>4th button</button>]
</script>

Document.createElement()

This method is used to create an HTML element with a given tag name. If we don’t specify any tag name or give any wrong one then an HTMLUnknownElement is created.

Example

<script>
let element = document.createElement('div')

element.innerText = 'This is created using DOM Method'

console.log(element)

// <div>This is created using DOM Method</div>
</script>

Parameters

tagName

tagName is said to be any type of HTML element tag we want to create like, p, div, span, button, header, or footer. 

options

options is an ElementCreationOptions object containing a single property named is.

Example

<script>
let element = document.createElement('div')

element.id = "create-element-id"

element.innerText = 'This is created using DOM Method'

console.log(element)

// <div id='create-element-id'>This is created using DOM Method</div>
</script>

Also read, JavaScript Functions | How does Function works in Js {Detail Explanation}

Document.createTextNode()

This method is used to create a text node. You can use this method to create a text node and add that node to any element. 

This method helps in creating text without any HTML tag.

Example

<p id='para'></p>

<script>

let para = document.querySelector('#para');

let node = document.createTextNode('Hello World')

console.log(node) // "Hello World"

para.append(node)

</script>

Document.createAttribute()

This method is used to create and return new attribute nodes. The node created using this method is simply implementing the Attr interface.

Attr interface is said to be the element’s attributes represented as an object.

Example

<script>

let element = document.createElement('div')

let attrib = document.createAttribute('attrib')

attrib.value = 'value'

element.setAttributeNode(attrib);

console.log(element.attributes.attrib)

// attrib='value'

</script>

These are the few methods that are used while working with attributes node,

Element.getAttribute()

This method is used to return the attribute node that is already set on the element.

<div class='learning' dom='hello'>Dom Methods</div>

<script>

let element = document.querySelector('.learning')

let res = element.getAttribute('dom')

console.log(res)

// hello

</script>

Element.setAttribute()

This method is used to set the new or replace the old attr node.

<div class='learning' dom='hello'>Dom Methods</div> 

<script> 
let element = document.querySelector('.learning') 
let res1 = element.getAttribute('dom')

console.log(res1) // hello 

element.setAttribute('dom', 'world')

let res2 = element.getAttribute('dom')

console.log(res2) // world

</script>

Element.hasAttribute()

This method returns a true value if the given element has specified attribute else returns false if not.

<div class='learning' dom='hello'>Dom Methods</div> 

<script> 
let element = document.querySelector('.learning') 
let res1 = element.hasAttribute('dom')
let res2 = element.hasAttribute('mod')

console.log(res1) // true
console.log(res2) // false

</script>

Element.removeAttribute()

This method removes the specified attribute present in the element.

<div class='learning' dom='hello'>Dom Methods</div> 

<script> 
let element = document.querySelector('.learning') 
element.removeAttribute('dom')

console.log(element)
// <div class='learning'>Dom Methods</div> 
</script>

Also read, An Easy Explanation of JavaScript Closure

Element.append()

This method is used to insert the set of Nodes or string objects to the given element after the last child of that element.

<ul class='learning'>
  <li>Apple</li>
  <li>Oranges</li>
</ul> 

<script> 
let element = document.querySelector('.learning') 
let child = document.createElement('li')

child.innerText = 'Banana'

element.append(child)

console.log(element)

/* <ul class='learning'>
  <li>Apple</li>
  <li>Oranges</li>
  <li>Banana</li>
</ul>  */
</script>

We can use appendChild() to perform the same function but there are a few differences between append() and appendChild(), let us see what they are:-

append() appendChild()
It allows you to append nodes and string objects. It only allows you to append node objects.
It doesn’t return anything. It returns appended node objects.
It can append numerous nodes and string objects. It only appends single-node objects.

Also read, What is a Callback Functions in JavaScript

Element.closest()

This method traverses up from the given element to the document root until it finds the ancestor which matches the given selector.

Example

<ul>
    <li>
        <strong class="myStrong">Nested</strong>
    </li>
    <li>Another list item ...</li>
</ul> 

<script> 
const myStrong = document.querySelector(".myStrong");
const containingList = myStrong.closest("ul");

console.log(containingList) // ul

</script>

Element.insertAdjacentHTML()

This method works similarly like innerHTML, allowing attaching HTML directly but with this method, you can choose the specific position where exactly you want to add your HTML.

Example

<ul>
    <li class='first-element'>Apple</li>
    <li class='middle-element'>Oranges</li>
    <li class='last-element'>Banana</li>
</ul> 

<script> 
const firstElement = document.querySelector(".first-element");
let newLi = "<li>PineApple</li>"

firstElement.insertAdjacentHTML("beforebegin", newLi)

console.log(firstElement) 

/* <ul>
    <li>PineApple</li>
    <li class='first-element'>Apple</li>
    <li class='middle-element'>Oranges</li>
    <li class='last-element'>Banana</li>
</ul>  */

</script>

Positions

beforebegin – given HTML is placed before the element, but only valid if the element is present in the DOM tree and has a parent element.

afterbegin – inside the element, just before its first-child

beforeend – inside the element, just before its last-child

afterend – given HTML is placed after the element, but only valid if the element is present in the DOM tree and has a parent element.

Also read, What is JavaScript Event Loop?

Element.replaceWith()

This method let you replace the given element with a set of Node or string objects.

Example

<div class='learning'>Hello World</div>

<script> 
const element = document.querySelector('.learning');
let anotherElement = document.createElement('div')

anotherElement.innerText = "Dom Methods"

element.replaceWith(anotherElement)

//<div>Dom Methods</div>
</script>

Element.matches()

This method checks and matches the element with the given query selector and returns a boolean value.

Example

<div class='learning dom'>Hello World</div>

<script> 
const element = document.querySelector('.learning');

let res = element.matches('.dom');

console.log(res) // true

</script>

Also read, How to debug JavaScript in browser?

Final Words

As new trends set in, a lot of companies are getting rid of jQuery and shifting back to more simple yet effective vanilla Javascript. So now it has become to have a better understanding of DOM and its methods. 

I hope You liked my article, if you did, do share it with more of your friends, family, and colleagues. Also, check out various excellent articles on different variety of topics like, React, Java, or Data Structure and Algorithms.

Aaquib Ahmedhttps://aaquib.netlify.app
Hi, I'm Aaquib Ahmed, a passionate self-taught frontEnd web developer based in Bangalore, India. I tend to make use of modern web technologies to build websites that look great, feels fantastic, and functions correctly. I am especially focusing on Reactjs.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments