A common job when working with Web Front-end JavaScript is manipulating the DOM. So what are DOM and JavaScript HTML DOM Elements? How to manipulate the DOM? Let’s find out in this lesson.
What is DOM in JS?
When you open a web page in the browser, the HTML content of the page is loaded and rendered (drawn) visually on the screen. To do that, the browser creates an object named Document Object Model called DOM, this object is a logical model that represents the structure of the HTML page.
The DOM of the HTML document is represented by a tree which is a collection of nested element boxes.Different elements will be classified differently, but the most important are 3 types: root node (document node), element node (element node), text node (text node).
Attributes of the element node
Properties | Meaning |
Id | Identifier – is unique for each element so it is often used for quick and direct DOM access. |
ClassName | ClassName – Also used for direct access as id, but 1 className can be used for multiple elements. |
tagName | HTML tag name. |
innerHTML | Returns the HTML code inside the current element. This HTML snippet is a string containing all the elements inside, including element nodes and text nodes. |
outerHTML | Returns the HTML code of the current element. In other words, outerHTML = tagName + innerHTML. |
textContent | Returns a character string containing the contents of all text nodes within the current element. |
attributes | Set of attributes like id, name, class, href, title… |
style | Set of the current element’s formatting settings. |
value | Get the value of the selected element into a variable. |
Methods for handling element nodes
Methods | Meaning |
getElementById(id) | Refers to a unique node whose id attribute is the same as the search id. |
getElementsByTagName(tagname) | Refers to all nodes with the tagName attribute that is the same as the tag name to be searched, or simply to find all DOM elements with the same HTML tag. If you want to access all tags in an HTML document, use document.getElementsByTagName(‘*’). |
getElementsByName(name) | References to all nodes with the name attribute to be found. |
getAttribute(attributeName) | Get the value of the attribute. |
setAttribute(attributeName, value) | Edit the value of the attribute. |
appendChild(node) | Add 1 child node to the current node. |
removeChild(node) | Remove 1 child node from the current node. |
Retrieve DOM elements in JS
There are two methods of accessing elements in the DOM:
- Indirect access (based on the position of the element relative to the root node to access)
- Direct access (based on identifiers such as id, class, tag). name … to retrieve).
In this article, we will only mention the direct access method because it is the more accurate and easier approach. There are 3 methods for direct access that are supported in all browsers:
- document.getElementById(‘id_to_find’)
- document.getElementsByTagName(‘div’)
- document.getElementsByClassName(‘name_to_find’)
Method 1. Using document.getElementById(‘id_to_find’)
document.getElementById(id) is used to find an element by its id – return HTMLElement or null if not found.
Syntax:
var element = document.getElementById("element_id");
Code sample:
<html>
<head>
<title>SAMPLE JS</title>
</head>
<body>
<div id="sample">Sample select Element</div>
<script>
var ele = document.getElementById('sample');
ele.innerHTML = "Hello LearnShareIT!";
</script>
</body>
</html>
The above example means: finding the element with the id of Sample, then changing the element content to Hello LearnShareIT!
Method 2. Using document.getElementsByTagName()
document.getElementsByTagName() method refers to all nodes with the tagName attribute that is the same as the tag name to be searched, or simply to find all DOM elements with the same HTML tag. If you want to access all tags in an HTML document, use document.getElementsByTagName(‘*’).
Syntax:
var element = document.getElementsByTagName("tag_name");
Code sample:
<!DOCTYPE html>
<html>
<body>
<h2>Using document.getElementsByTagName</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var arrElement = document.getElementsByTagName("p");
for (var x = 0; x < arrElement.length; x++) {
arrElement[x].innerHTML = "Wellcome to LearnShareIT";
}
</script>
</body>
</html>
The above code converts the content of the <p> tags to: Wellcome to LearnShareIT
Method 3: Using document.getElementsByClassName(‘name_to_find’)
The getElementsByClassName method finds all elements with the given class attribute. It also returns HTMLCollection.
Syntax:
var element = document.getElementsByClassName(“class_name”); |
Code sample:
var arr = document.getElementsByClassName("Sample");
//access the second element found
arr[1].innerHTML = "Hi";
Change element attributes in DOM
Once you have selected the element in the DOM, you can change the properties associated with the element, for example change the content using the innerHTML property.
For example, the HTML <img> element as known has the src attribute to indicate the image URL that the tag displays, known it has an attribute named src, then after having this word from the DOM, you can can read, assign the attribute and it will update the HTML page if assigned.
Code sample:
<!DOCTYPE html>
<html>
<body>
<h2>Change element attributes in DOM</h2>
<img id="logoimg" src="black.png" alt="" />
<script>
var imglogo = document.getElementById("logoimg");
imglogo.src = "https://learnshareit.com/wp-content/uploads/2022/09/cropped-learnshareit-logo.png";
</script>
</body>
</html>
or if you want to change the href attribute in the <a> link element, we have the following example:
<!DOCTYPE html>
<html>
<body>
<h2>Change element attributes in DOM</h2>
<a href="https://www.google.com/">Google.com</a>
<script>
var arrlink = document.getElementsByTagName("a");
arrlink[0].href = "https://learnshareit.com/";
</script>
</body>
</html>
Retrieve and change the element’s CSS property, the html tag
To do this, you first need to define the element. Then retrieve the css property of the div block by retrieving the style attribute of the specified element. Finally change the background-color property by reassigning the style.backgroundColor property to the element.
Code sample:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to change color</p>
<button onclick="changeColor()">Change</button>
<script>
function changeColor() {
var arr_p_element = document.getElementsByTagName('p');
for (var i = 0; i <= arr_p_element.length - 1; i++) {
var var_Element = arr_p_element[i];
var_Element.style.color = "green";
var_Element.style.fontSize = "20px";
}
}
</script>
</body>
</html>
So together we have learned the basics of JavaScript HTML DOM Elements and how to manipulate the DOM. Although that’s just the surface knowledge, you can also see how important and beneficial the DOM is.
Below we have compiled a list of tutorials related to DOM Elements that may be of interest to you:
- Get an Element by Name attribute using JavaScript
- Add a class to the Body element using JavaScript
- Add Line breaks to a Textarea using JavaScript
- Change the Text of a Div Element using JavaScript
- Loop through all DOM elements using JavaScript
- Get Child Element by Class using JavaScript
- Disable an Element by ID using JavaScript
- Change the Text of a Label element using JavaScript
- Get the Value/Text of Select or Dropdown on Change using JS
- Insert an Element into the Body tag using JavaScript
- Append text to an Element using JavaScript
- Set the “disabled” Attribute using JavaScript
- Check if an Element does NOT have specific Class using JS
- Hide an Element by Class using JavaScript
- Set the “required” Attribute using JavaScript
- Set the Width and Height of an Element using JavaScript
- Show/Hide an element on Radio button Selection using JS
- Clear the Content of a Div element using JavaScript
- Call a function if an Element exists using JavaScript
- Append text to a Paragraph element using JavaScript
- Add an ID attribute to an Element using JavaScript
- Get Elements by multiple Class Names in JavaScript
- Clear Input fields after Submit using JavaScript
- How to create a style tag using JavaScript
- Remove the “disabled” Attribute using JavaScript
- Check if an element is a checkbox using javascript
- Show/hide a div element by id using javascript
- Update all dom elements with a specific class using js
- Solution To Create An Element With ID Attribute Using JS
- How To Change Background Color On Click In JavaScript?
- How To Clear Input Fields After Submit Using JavaScript
- Check If An Element Is Read-Only Using JavaScript
- Create An Image Element In JavaScript
- How To Set A Radio Button To Checked/Unchecked In Javascript?
- AddEventListener To The Results From querySelectorAll Using JavaScript
- How To Get The Text Of A Div Element Using JavaScript
- Select elements by Multiple IDs using JS
- Remove CSS Style Property from an Element using JavaScript
- Check if Element’s Style contains CSS property using JavaScript
- Hide an Element after a few Seconds using JavaScript
- Override an Element’s !important Styles using JavaScript
- Show a `hidden` Div on Hover using JavaScript
- Move the Cursor to an Input field using JavaScript
- “TypeError: form.submit is not a function” in JavaScript
- Get the Status Code of a Fetch HTTP Response using JavaScript
- Get an Element’s CSS Display Value in JavaScript
- Add attribute to multiple Elements in JavaScript
- TypeError: getElementById is not a function in JavaScript
- Clone an Element and change its ID using JavaScript
- Clear the Value of a Textarea using JavaScript
- Clear a Textarea on Button click using JavaScript
- Create an Element with Style attribute in JavaScript
- Remove the focus from an Element using JavaScript
- Detect if a Browser tab has Focus using JavaScript
- Loop through all Form elements using JavaScript
- Get the Index of a Child node using JavaScript
- Get the First element with specific Class name using JavaScript
- Remove all Styles from an Element using JavaScript
- Get all Elements in a Form using JavaScript
- Remove all Event Listeners from an Element using JavaScript
- Append text to Textarea using JavaScript
- Remove the ID attribute from an Element using JavaScript
- Get an Element by Href Attribute using JavaScript
- Get the first Child of specific Type using JavaScript
- Remove the parent Element of a Node using JavaScript
- Set the Values of Input type Date and Time using JavaScript
- Get element by ID by partially matching String using JavaScript
- Check if an Element is Required using JavaScript
- Check if data attribute Exists using JavaScript
- Check if a Div contains specific Text using JavaScript
- Show/Hide a Form on button click using JavaScript
- Remove multiple classes from an Element using JavaScript
- Remove all Classes from an Element using JavaScript
- Check if an Element is Disabled using JavaScript
- Set styles on the Body Element using JavaScript
- How to Clear Text Selection using JavaScript
- How to Check if an Element is a Div using JavaScript
- Get all elements whose ID starts with specific String in JS
- Get all DOM Elements by its Attribute in JavaScript
- Get the nth element of the same type using JavaScript
- Get the nth child of an Element using JavaScript
- Check if a Window has Focus using JavaScript
- Find the Previous Element with specific Class using JS
- Remove a class from the Body element using JavaScript
- Remove all Classes except One using JavaScript
- Show a Div when a Select option is Selected using JavaScript
- Get Child Element by ID using JavaScript
- Get Element by aria-label using JavaScript
- Change the Text of a Link element using JavaScript
- Count the Elements in a Div using JavaScript
- Get nth-child using querySelector in JavaScript
- Change the Text of a Span element using JavaScript
- QuerySelector attribute contains using JavaScript
- Remove a DOM element by ID using JavaScript
- Hide all elements by Class using JavaScript

Hi guys, wellcome to LearnShareIt. I’m Tiffany and I’m also who responsible for the quality of this website’s content. I previously worked on software development projects for ten years as a developer. Hopefully, our project will bring a lot of value to the community.
Job: Programmer/Project management
Major: IT
Programming Languages: Python, C, HTML, MySQL, SQL Server, C#, C++, Javascript, CSS, Java, VB