DEV Community

Cover image for DOM Manipulation in JS
Tanmay Agrawal
Tanmay Agrawal

Posted on

DOM Manipulation in JS

This post consist of only few important DOM methods, But I hope this will get you started in making your first attempt to DOM manipulation by yourself. Use this as a guide

What is DOM?
Document Object Model : is a structured representation of HTML documents, allows JavaScript to access HTML elements and styles to manipulate them.

image discription

The DOM has a tree structure as shown above.

document is the special object that is the entry point of the DOM.
example document.querySelector()

*Note: DOM is not the part of the JS, instead it is a part of the web API, these web API interacts with the JS. Some similar API are fetch, timers etc.

JavaScript DOM manipulators are methods and properties that enable the manipulation and modification of elements in the Document Object Model (DOM). These manipulators allow you to dynamically alter the content, structure, and style of web pages, creating interactive and dynamic user experiences. Here are some commonly used JavaScript DOM manipulators:

document.getElementById(): Retrieves an element from the DOM based on its unique id.

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

document.getElementsByClassName(): Retrieves a collection of elements from the DOM based on their class name.

const elements = document.getElementsByClassName('myClass');
Enter fullscreen mode Exit fullscreen mode

document.getElementsByTagName(): Retrieves a collection of elements from the DOM based on their tag name.

const elements = document.getElementsByTagName('div');
Enter fullscreen mode Exit fullscreen mode

document.querySelector(): Retrieves the first element from the DOM that matches a specified CSS selector.

const element = document.querySelector('.myClass');
Enter fullscreen mode Exit fullscreen mode

document.querySelectorAll(): Retrieves a collection of elements from the DOM that match a specified CSS selector.

const elements = document.querySelectorAll('p');
Enter fullscreen mode Exit fullscreen mode

element.innerHTML: Sets or gets the HTML content of an element.

const element = document.getElementById('myElementId'); 
element.innerHTML = 'New content';
Enter fullscreen mode Exit fullscreen mode

element.style: Manipulates the CSS styling of an element.

const element = document.getElementById('myElementId'); 
element.style.color = 'red';
Enter fullscreen mode Exit fullscreen mode

element.classList: Manipulates the class attributes of an element.

const element = document.getElementById('myElementId'); element.classList.add('newClass');
Enter fullscreen mode Exit fullscreen mode

document.createElement(): Creates a new element in the DOM.

const newElement = document.createElement('div');
Enter fullscreen mode Exit fullscreen mode

element.appendChild(): Appends a child element to a parent element.

const parent = document.getElementById('parentElementId'); parent.appendChild(newElement);

Enter fullscreen mode Exit fullscreen mode

These JavaScript DOM manipulators provide a powerful set of tools for dynamically interacting with the content and structure of web pages. They allow you to create, modify, and delete elements, as well as change their content, attributes, and styles, enabling the creation of dynamic and interactive web applications.

Changing and modifying elements

Accessing Content:

To get the content of an element, use innerHTML or innerText properties.

const element = document.getElementById('myElementId'); const content = element.innerHTML; // Gets the HTML content const textContent = element.innerText; // Gets the text content
Enter fullscreen mode Exit fullscreen mode

Setting Content:

To set the content of an element, use the same innerHTML or innerText properties.

const element = document.getElementById('myElementId'); element.innerHTML = '<p>New HTML content</p>'; // Sets the HTML content element.innerText = 'New text content'; // Sets the text content
Enter fullscreen mode Exit fullscreen mode

Changing innerHTML:

You can change the innerHTML property of an element to modify its HTML content.

const element = document.getElementById('myElementId'); element.innerHTML = '<p>New HTML content</p>';
Enter fullscreen mode Exit fullscreen mode

Adding Event Listeners:

Event listeners enable you to respond to user interactions, such as clicks or keypresses.

const button = document.getElementById('myButton'); button.addEventListener('click', function() {     // Your event handling code here });
Enter fullscreen mode Exit fullscreen mode

Creating Elements:

You can create new elements using document.createElement() and modify their attributes and content before appending them to the DOM.

const newElement = document.createElement('div'); newElement.id = 'newDiv'; newElement.textContent = 'New content'; document.body.appendChild(newElement);
Enter fullscreen mode Exit fullscreen mode

**InsertAdjacentHTML :

<div id="myDiv">Initial content</div>
<button onclick="addContent()">Add Content</button>
Enter fullscreen mode Exit fullscreen mode
function addContent() {
    const myDiv = document.getElementById('myDiv');
    myDiv.insertAdjacentHTML('afterbegin', '<p>New content at the beginning</p>');
    myDiv.insertAdjacentHTML('beforeend', '<p>New content at the end</p>');
}
Enter fullscreen mode Exit fullscreen mode

Can also add elements

function addElement() {
    const myDiv = document.getElementById('myDiv');
    const newElement = document.createElement('p');
    newElement.textContent = 'New element';
    myDiv.insertAdjacentElement('afterbegin', newElement);
}
Enter fullscreen mode Exit fullscreen mode

Or adjacent texts

function addText() {
    const myDiv = document.getElementById('myDiv');
    myDiv.insertAdjacentText('afterbegin', 'New text');
}
Enter fullscreen mode Exit fullscreen mode

Getting User Inputs

Lets see this with an examples

Input fields

<select id="mySelect">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
</select>
<button onclick="getSelect()">Get Select</button>

Enter fullscreen mode Exit fullscreen mode
function getSelect() {
    const select = document.getElementById('mySelect');
    const selectedOption = select.options[select.selectedIndex].value;
    console.log(selectedOption);
}
Enter fullscreen mode Exit fullscreen mode

Here at quertSelectors or getElementById can have .value method to get the value of the input field of HTML.

Select Dropdown

   <select id="mySelect">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
</select>
<button onclick="getSelect()">Get Select</button>

Enter fullscreen mode Exit fullscreen mode
function getSelect() {
    const select = document.getElementById('mySelect');
    const selectedOption = select.options[select.selectedIndex].value;
    console.log(selectedOption);
}
Enter fullscreen mode Exit fullscreen mode

Radio Buttons

<input type="radio" name="myRadio" value="option1" id="option1"> Option 1
<input type="radio" name="myRadio" value="option2" id="option2"> Option 2
<button onclick="getRadio()">Get Radio</button>
Enter fullscreen mode Exit fullscreen mode
function getRadio() {
    const radio1 = document.getElementById('option1');
    const radio2 = document.getElementById('option2');
    if (radio1.checked) {
        console.log('Option 1 selected');
    } else if (radio2.checked) {
        console.log('Option 2 selected');
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)