DEV Community

Cover image for JavaScript DOM(Document Object Model)
Souvik Jana
Souvik Jana

Posted on • Updated on

JavaScript DOM(Document Object Model)

We would be discussing JavaScript DOM in this article which is a very important topic to learn when you're starting your journey with JavaScript as well as preparing for JS interview. This would help you to understand how Vanilla JS works.

What is DOM in Javascript?

DOM is a Javascript object to manipulate HTML elements. In simple words, we use DOM to select HTML elements and manipulate what user sees on the browser.

How to select HTML element?

We generally use global variable document to select the required HTML element. These are some of the ways to select HTML element :

  • querySelector() :
const element = document.querySelector(".className");
const element = div.querySelector("#id");
Enter fullscreen mode Exit fullscreen mode

querySelector() method works on document, HTML tags(h1, p, div...) to select one HTML element with the given .className or #id. This method will return the 1st matched element from the DOM or document. If we apply this method on some html tags then that would help to select childs of that tag whereas document helps to select its child elements (i.e. all elements in HTML are childs of document).

  • querySelectorAll() :
const elements = document.querySelectorAll(".className");
const elements = div.querySelectorAll("tagName");
Enter fullscreen mode Exit fullscreen mode

querySelectorAll() method returns an array with all the matches found. We use this to select multiple elements having same CSS class or tag.

Recommended to use querySelectorAll(), when we have to attach the same event handler or functionality to multiple elements, otherwise if we try to select multiple elements using tag name or class and try to attach different event handler depending on the element's position in the returned array then it might happen that position of the element in the HTML document changes in future which will produce wrong output eventually since event handlers need to be altered in that case.

  • getElementById() :
const element = document.getElementById("id")
Enter fullscreen mode Exit fullscreen mode

getElementById() is an another method to select an element using id. We could do the same thing using querySelector() but we 're using "#" before the "id" while doing the same using querySelector(), in this case "#" is not required to select as we are using getElementById()

It's not like that we can only select existing HTML elements only, we can also create HTML element using DOM.

How to create HTML element?

There're 3 steps to create a new HTML element. Follow the attached code to do so.

const newElement = document.createElement("tagName"); //to create a new element with the given tag(p, div,...)
newElement.textContent = "textContentForNewElement"; //to add textContent to the new element
document.querySelector("parentTagName").appendChild(newElement); //to append the new element in the any existing element of the document as a child 
Enter fullscreen mode Exit fullscreen mode

The above mentioned code will do the following

  • create new element,
  • add content for that,
  • append the newly created element to the HTML document as a child of the given parent tag.

What to do with the selected / newly created HTML element?

Once it's selected, we can manipulate as per our choice to fulfill the requirement - we can

  • get content or value of an element,
  • change content or value of an element,
  • change styles, attributes, add or remove CSS classes from an element.
Get content or value of an element?
const element = document.querySelector(".className");
let msg = element.textContent;
Enter fullscreen mode Exit fullscreen mode

This is for <p>, <div>... tags which contain some text as content of the page, we can get that content as mentioned above to do some work.

const element = document.querySelector("#id");
let msg = element.value;
Enter fullscreen mode Exit fullscreen mode

This is for input elements like textbox where we take some input from user and do our work after that.

Change content or value of an element?

For <p>, <div>... tags

const element = document.querySelector(".className");
element.textContent = "newContent";
Enter fullscreen mode Exit fullscreen mode

For input elements like textbox

const element = document.querySelector(".className");
element.value = "newValue";
Enter fullscreen mode Exit fullscreen mode

NOTE :- Notice when we are using textContent and when we're using value.

Change styles, attributes, add or remove CSS classes from an element?
  • To change style of an element, we need to do the following after selecting the element from the DOM :
element.style.backgroundColor = "color"; //this is to set or change the background color of an element
Enter fullscreen mode Exit fullscreen mode
  • To set or change some attributes of an element, do the following step after selecting the element from the DOM :
element.src = "pathOfTheImageFile"; //this is to set or change the `src` attribute of an `<img>` element
Enter fullscreen mode Exit fullscreen mode
  • Add the CSS class to an element
element.classList.add("className");
Enter fullscreen mode Exit fullscreen mode
  • Remove the CSS class from an element
element.classList.remove("className");
Enter fullscreen mode Exit fullscreen mode
  • Toggle the CSS class from an element i.e. remove the class from the element if it's present else add the class to the selected element.
element.classList.toggle("className");
Enter fullscreen mode Exit fullscreen mode
  • To get whether the CSS class is present or not with the selected element, it returns true or false based on the availability.
var isPresent = element.classList.contains("className");
Enter fullscreen mode Exit fullscreen mode

As you all know there are so many methods, concepts and ways to work with Javascript DOM. These are some of those ways that I used while I was learning DOM. Lastly, I will add one more part of it to mention how to add event along with eventHandler for an element which is one of the things that we can perform once we have the element selected.

How to add event to an element?

There're tons of events which we can attach to an element, once that is selected. This is how you can attach one event to an element.

element.addEventListener("nameOfTheEvent", "eventHandler");
Enter fullscreen mode Exit fullscreen mode

if there's any event that we want to execute once then we can remove that event as well once it's executed.

element.removeEventListener("nameOfTheEvent", "eventHandler");
Enter fullscreen mode Exit fullscreen mode

I have decided to discuss about DOM only in this blog, events will take may be another blog post to discuss.

Want to read more about events?

Read here


Comments?

Please feel free to share your comments on this blog post. Happy Learning :)

Top comments (2)

Collapse
 
rafavls profile image
Rafael

DOM had me very confused and this post made it so much clearer. Thank you!

Collapse
 
sjsouvik profile image
Souvik Jana

Thanks Rafael! Stay tuned for more such blogs :)