DOM Manipulation in JS
Tags: javascript, beginners, webdev, tutorial
Published: 2023-10-19 06:21:24

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fx0fok1g59qgwnlekrdw.png)

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`.
    
```js
const element = document.getElementById('myElementId');
```
    
**document.getElementsByClassName():** Retrieves a collection of elements from the DOM based on their class name.
    
```js
const elements = document.getElementsByClassName('myClass');
```
    
**document.getElementsByTagName():** Retrieves a collection of elements from the DOM based on their tag name.
    
```js
const elements = document.getElementsByTagName('div');
```
    
**document.querySelector():** Retrieves the first element from the DOM that matches a specified CSS selector.
    
```js
const element = document.querySelector('.myClass');
```
    
**document.querySelectorAll():** Retrieves a collection of elements from the DOM that match a specified CSS selector.
    
```js
const elements = document.querySelectorAll('p');
```
    
**element.innerHTML:** Sets or gets the HTML content of an element.
    
```js
const element = document.getElementById('myElementId'); 
element.innerHTML = 'New content';
```
    
**element.style:** Manipulates the CSS styling of an element.
    
```js
const element = document.getElementById('myElementId'); 
element.style.color = 'red';
```
    
**element.classList:** Manipulates the class attributes of an element.
    
```js
const element = document.getElementById('myElementId'); element.classList.add('newClass');
```
    
**document.createElement():** Creates a new element in the DOM.
    
```js
const newElement = document.createElement('div');
```
    
**element.appendChild():** Appends a child element to a parent element.
    
```js
const parent = document.getElementById('parentElementId'); parent.appendChild(newElement);

```

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.

```js
const element = document.getElementById('myElementId'); const content = element.innerHTML; // Gets the HTML content const textContent = element.innerText; // Gets the text content
```
    
**Setting Content:**
    
To set the content of an element, use the same `innerHTML` or `innerText` properties.
    
```js
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
```
    
**Changing innerHTML:**
    
You can change the `innerHTML` property of an element to modify its HTML content.
```js
const element = document.getElementById('myElementId'); element.innerHTML = '<p>New HTML content</p>';
```
    
**Adding Event Listeners:**
    
Event listeners enable you to respond to user interactions, such as clicks or keypresses.
    
```js
const button = document.getElementById('myButton'); button.addEventListener('click', function() {     // Your event handling code here });
```
    
**Creating Elements:**
    
You can create new elements using `document.createElement()` and modify their attributes and content before appending them to the DOM.

```js
const newElement = document.createElement('div'); newElement.id = 'newDiv'; newElement.textContent = 'New content'; document.body.appendChild(newElement);
```


**InsertAdjacentHTML : 
```html
<div id="myDiv">Initial content</div>
<button onclick="addContent()">Add Content</button>
```

```js
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>');
}
```

Can also add elements

```js
function addElement() {
    const myDiv = document.getElementById('myDiv');
    const newElement = document.createElement('p');
    newElement.textContent = 'New element';
    myDiv.insertAdjacentElement('afterbegin', newElement);
}
```

Or adjacent texts

```js
function addText() {
    const myDiv = document.getElementById('myDiv');
    myDiv.insertAdjacentText('afterbegin', 'New text');
}
```

## Getting User Inputs

Lets see this with an examples

Input fields

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

```

```js
function getSelect() {
    const select = document.getElementById('mySelect');
    const selectedOption = select.options[select.selectedIndex].value;
    console.log(selectedOption);
}
```

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

Select Dropdown

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

```


```js
function getSelect() {
    const select = document.getElementById('mySelect');
    const selectedOption = select.options[select.selectedIndex].value;
    console.log(selectedOption);
}
```

Radio Buttons
   
```html
<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>
```

```js
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');
    }
}
```