JavaScript HTML DOM Elements

JavaScript HTML DOM Elements

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

PropertiesMeaning
IdIdentifier – is unique for each element so it is often used for quick and direct DOM access.
ClassNameClassName – Also used for direct access as id, but 1 className can be used for multiple elements.
tagNameHTML tag name.
innerHTMLReturns the HTML code inside the current element. This HTML snippet is a string containing all the elements inside, including element nodes and text nodes.
outerHTMLReturns the HTML code of the current element. In other words, outerHTML = tagName + innerHTML.
textContentReturns a character string containing the contents of all text nodes within the current element.
attributesSet of attributes like id, name, class, href, title…
styleSet of the current element’s formatting settings.
valueGet the value of the selected element into a variable.

Methods for handling element nodes

MethodsMeaning
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:

  1. document.getElementById(‘id_to_find’)
  2. document.getElementsByTagName(‘div’)
  3. 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:

Leave a Reply

Your email address will not be published. Required fields are marked *