DOM Manipulation: How to Use Its Methods to Interact with Web Pages
Tags: dom, html, javascript, webdev
Published: 2023-02-21 20:54:59

The Document Object Model (DOM) provides a wide range of methods that allow web developers to access and manipulate the content, structure, and style of web pages dynamically. Here are some of the most commonly used DOM methods:

## getElementById()
This method is used to access a specific element in the Document Object Model (DOM) tree using its ID

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of getElementById</title>
</head>
<body>
    <h1>Welcome to my Website</h1>
    <p>Thanks for visiting my website. Please feel free to explore the various pages and sections.</p>

    <div id="content">
        <h2>Latest News</h2>
		<p>Check out our latest blog post on the benefits of meditation.</p>
    </div>
<script>
    //select the Element with ID content
    let content = document.getElementById('content');
   
    //update content
    content.innerHTML = 
    "<h2>Update Content</h2><p>This is updated content using JavaScript Method getElementById.</p>."
</script>
</body>
</html>
```
Output

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zwgt7n6spzuplcs2d43.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zwgt7n6spzuplcs2d43.png)

In this example, the `getElementById()` method is used to select the element with ID "content". The `innerHTML` property is then used to replace the existing content of that element with new HTML content. This could be useful, for example, if you wanted to dynamically update the content of a specific section of a web page in response to user input or some other event.

## getElementsByTagName()
`getElementsByTagName()` method is used to select all elements of a specific tag name in the Document Object Model (DOM) tree

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of getElementsByTagName()</title>
</head>
<body>
    <h1>Welcome to my Website</h1>
    <p>Thanks for visiting my website. Please feel free to explore the various pages and sections.</p>
	<ul>
		<li>Home</li>
		<li>About</li>
		<li>Contact</li>
	</ul>

    <script>
            //select <li> elements on the page
            let listItems = document.getElementsByTagName('li');
            //Loop through the list items and update their content
            for(let i = 0; i < listItems.length; i++){
                listItems[i].innerHTML = "Page " + (i+1) + ": " + listItems[i].innerHTML;
            }
    </script>

</body>
</html>
```
output

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0nluaiepdh2fqr6b0sf.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0nluaiepdh2fqr6b0sf.png)

In this example, the `getElementsByTagName()` method is used to select all `<li>` elements on the page. A for loop is then used to iterate through each of the selected elements and modify their content by adding a page number before the existing text.

## createElement()
The `createElement()` method is used to dynamically create and add an HTML element to a webpage using JavaScript

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of createElement()</title>
</head>
<body>
    <h1>Welcome to my Website</h1>
    <div id="content">
		<h2>Latest News</h2>
		<p>Check out our latest blog post on the methods of DOM.</p>
	</div>
    <script>
        //create a new paragraph element 
        let newParagraph = document.createElement('p');

        //Add text content to the new element
        newParagraph.textContent = "Stay tuned for more updates.";

        //add the new element to the "cotent" div
        let contentDiv = document.getElementById('content');
        contentDiv.appendChild(newParagraph);
    </script>
</body>
</html>
```
Output

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdin3f6z38ze6f6nuj3a.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdin3f6z38ze6f6nuj3a.png)

In this example, the `createElement()` method is used to create a new `<p>` element. The `textContent` property is then used to set the text content of the new element. Finally, the `appendChild()` method is used to add the new element to the existing div element with ID "content". This could be useful for dynamically adding content to a webpage in response to user actions or other events.

## setAttribute()
The `setAttribute()` method is used to dynamically add an attribute to an HTML element using JavaScript

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of setAttribute()</title>
</head>
<body>
    <h1>Welcome to my website</h1>
	<p>Thanks for visiting my website. Please feel free to explore the various pages and sections.</p>
	<img id="myImage" src="img.jpeg" alt="A beautiful mountain landscape" width="300">
	<div><button onclick="changeImage()">Change Image</button></div>
    <script>
        function changeImage(){
            //select the image element
            let myImage = document.getElementById('myImage');

            //change the image src using setAttribute
            myImage.setAttribute('src','newImg.jpg');
            myImage.setAttribute('alt','A stuning sunset over the ocean')
        }
    </script>
</body>
</html>
```
Output

![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rijx46a3cmh05q9x4j9.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rijx46a3cmh05q9x4j9.png)
after clicking on the Change Image button
![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/al7p99k8e3te0u5gido6.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/al7p99k8e3te0u5gido6.png)
In this example, the `setAttribute()` method is used to dynamically change the `src` and `alt` attributes of an `<img>` element when the user clicks a button. The `changeImage()` function selects the image element using its ID, then uses `setAttribute()` to change the value of the `src` and `alt` attributes. This could be useful for dynamically updating the content and behavior of a webpage in response to user actions or other events.

## getAttribute()

The `getAttribute()` method is used to retrieve the value of a specific attribute from an HTML element using JavaScript

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of getAttribute()</title>
</head>
<body>
    <h1>Welcome to my website</h1>
	<p>Thanks for visiting my website. Please feel free to explore the various pages and sections.</p>
	 <p><button onclick="showAlt()">Show Alt Text</button></p>
    <script>
        function showAlt(){
             //select the image element
             let myImage = document.getElementById('myImage');

            // Get the value of the "alt" attribute using getAttribute()
            let altText =  myImage.getAttribute('alt');

            //display alt value in alert
            alert(altText);
        }
    </script>
</body>
</html>
```
Output
![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rq1rszbljirqgidqqp0t.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rq1rszbljirqgidqqp0t.png)

In this example, the `getAttribute()` method is used to retrieve the value of the `alt` attribute from an `<img>` element when the user clicks a button. The `showAlt()` function selects the image element using its ID, then uses `getAttribute()` to retrieve the value of the `alt` attribute and store it in a variable. Finally, an `alert` box is used to display the value of the `alt` attribute to the user. This could be useful for accessing and using specific attributes of HTML elements in your JavaScript code.

## innerHTML
The `innerHTML` property is used to dynamically update the content of an HTML element using JavaScript

```
<!DOCTYPE html>
<html>
<head>
	<title>Example of innerHTML</title>
</head>
<body>
	<h1>Welcome to my website</h1>
	<p>Thanks for visiting my website. Please feel free to explore the various pages and sections.</p>
	<div id="content">
		<h2>Latest News</h2>
		<p>Check out our latest blog post on the benefits of meditation.</p>
	</div>
	<button onclick="addContent()">Add Content</button>
	<script>
		function addContent() {
			// Select the content div
			var contentDiv = document.getElementById("content");

			// Use innerHTML to add new content to the div
			contentDiv.innerHTML += "<h3>New Section</h3><p>Here is some new content that has been dynamically added to the page!</p>";
		}
	</script>
</body>
</html>

```
In this example, the `innerHTML` property is used to dynamically add new content to a `<div>` element when the user clicks a button. The `addContent()` function selects the content div using its ID, then uses `innerHTML` to append new HTML code to the existing content of the div. This could be useful for dynamically updating the content and structure of a webpage in response to user actions or other events. However, it's important to be careful when using `innerHTML`, as it can potentially introduce security vulnerabilities if not used properly.

## removeChild()
The `removeChild()` method is used to remove an HTML element from the DOM using JavaScript

```
<!DOCTYPE html>
<html>
<head>
	<title>Example of removeChild()</title>
</head>
<body>
	<h1>Welcome to my website</h1>
	<p>Thanks for visiting my website. Please feel free to explore the various pages and sections.</p>
	<ul id="myList">
		<li>Item 1</li>
		<li>Item 2</li>
		<li>Item 3</li>
		<li>Item 4</li>
	</ul>
	<button onclick="removeItem()">Remove Item</button>
	<script>
		function removeItem() {
			// Select the list element and its first child
			var myList = document.getElementById("myList");
			var firstItem = myList.firstElementChild;

			// Use removeChild() to remove the first item from the list
			myList.removeChild(firstItem);
		}
	</script>
</body>
</html>

```
In this example, the `removeChild()` method is used to remove the first item from a `<ul>` element when the user clicks a button. The `removeItem()` function selects the list element using its ID, then selects its first child element using the firstElementChild property. Finally, `removeChild()` is used to remove the first item from the list by passing in the first child element as an argument. This could be useful for dynamically modifying the content and structure of a webpage in response to user actions or other events.

To see working examples of DOM manipulation using JavaScript, check out my GitHub repository: https://github.com/SidraMaq/DOM

Thanks for reading! I hope you found this post informative and helpful. If you have any questions or feedback, please feel free to leave a comment below. And don't forget to check out my GitHub repository for working examples of DOM manipulation using JavaScript.