DEV Community

Dylan Rhinehart
Dylan Rhinehart

Posted on

DOM Manipulation Basics: Vanilla JS

The Document Object Model (DOM) is an essential part of web development, and JavaScript allows us to manipulate the DOM in powerful ways. The DOM is a tree-like structure that represents the HTML of a web page, and by using JavaScript, we can add, remove, and modify elements in the DOM to create dynamic and interactive web pages.

One common way to manipulate the DOM is through the document object, which is a global object in JavaScript that represents the HTML document. Using the document object, we can select elements on the page, access their properties, and modify their content or style.

For example, to select an element by its unique ID, we can use the document.getElementById method:

const element = document.getElementById('my-element');
Enter fullscreen mode Exit fullscreen mode

You can also use document.querySelector method, this method can prove more useful at times.

//To get an element by ID
const element = document.querySelector('#my-element-id');

//To get an element by Class
const element = document.querySelector('.my-element-class');
Enter fullscreen mode Exit fullscreen mode

Note the difference between ID and Class. To find an ID you must use '#myId'. To find a Class you must use '.myClass'.

Once we have selected an element, we can modify its content using the innerHTML property:

element.innerHTML = 'Hello, world!';
Enter fullscreen mode Exit fullscreen mode

We can also modify the style of an element using the style property: = 'red';
Enter fullscreen mode Exit fullscreen mode

In addition to these basic techniques, we can use methods such as createElement and appendChild to add new elements to the DOM, and removeChild to remove elements.

Enter fullscreen mode Exit fullscreen mode

Overall, the DOM is a powerful tool for interacting with web pages, and learning to manipulate it is an important part of becoming a proficient JavaScript developer. Whether we are building simple websites or complex applications, the ability to manipulate the DOM is an essential skill that every JavaScript developer should have in their toolkit.


Top comments (0)