ID and Class attributes are the most common selectors that widely used to target the HTML DOM while working with JavaScript. In this method we target the Single HTML element within the DOM tree using its ID attribute. While using ID, it always returns a single node of HTML DOM.

ID and Class attributes are the most common selectors that widely used to target the HTML DOM while working with JavaScript. Have you ever thought why we mostly prefer to use the id and class while many of the methods are available to target the HTML Elements in JavaScript?

First of all, we look at all the methods to target the HTML Elements using JavaScript.

For reference you can check the multiple examples below.

How to target HTML elements using ‘id’?



    <div id="test"></div>
    <script>
        //we want to print "Hello World inside div"
        document.getElementById("test").innerHTML="Hello World!";
    </script>
Try Yourself

In this method we target the Single HTML element within the DOM tree using its ID attribute. While using ID, it always returns a single node of HTML DOM.

The most important thing is that using two or more HTML elements with the same ID on the same web page can produce the unexpected error, therefore, we should be careful using the ID attribute while creating the web page.

How to target HTML Elements using ‘class’?



    <!--Different HTML tags with same classes-->
    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    
    <script>
        document.getElementsByClassName("test")[0].innerHTML="This Heading";
        document.getElementsByClassName("test")[1].innerHTML="This is div";
        document.getElementsByClassName("test")[2].innerHTML="This is paragraph";
        document.getElementsByClassName("test")[3].innerHTML="This is span";
    </script>
Try Yourself

In this method we target one or more HTML Elements with the same class name. When we target HTML Elements with the class name, each HTML element with the same class becomes the part of that class, it returns a list of nodes (referred to as NodeList in the console) instead of a single node where each node can be referred with the index number like given in above example.

The index number of each node is decided by its appearance on the web page. For e.g. the index of the very first node is referred to as [0] and second as [1] and so on. If the position of any node is changed on the webpage then its index will be also changed accordingly and it might affect the index of rest upcoming nodes also.

Even we target a single element with the class name, it returns a list of nodes but the difference is that there is only a single node present in that list.

Therefore it is a better idea to use class names but in a structured way.

We will study more about classes in further chapters

How to target HTML Elements using ‘tag name’?



    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    <span class="test"></span>
    <script>
        document.getElementsByTagName("H1")[0].innerHTML="This Heading";
        document.getElementsByTagName("DIV")[0].innerHTML="This is div";
        document.getElementsByTagName("P")[0].innerHTML="This is paragraph";
        document.getElementsByTagName("SPAN")[0].innerHTML="This is first span";
        document.getElementsByTagName("SPAN")[1].innerHTML="This is second span";
    </script>
Try Yourself

In this method we target one or more HTML elements with their tag name. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

How to target HTML Elements using the ‘name’ attribute?



    <!--Different HTML tags with same classes-->
    <form action="">
        <div><input type="text" name="fname" placeholder="first name" value="John"/></div><br/>
        <div><input type="text" name="lname" placeholder="last name" value="Doe"/></div><br/>
        <div><input type="email" name="email" placeholder="email" value="john@progrramers.com"/></div><br/>
        <div><input type="url" name="website" placeholder="website" value="https://progrramers.com"/></div><br/>
        <div><input type="button" name="submit" value="Save" onclick="formdata()"/></div><br/>
    </form>
    <p name="test"></p>
    <script>
        function formdata(){
            var fname=document.getElementsByName('fname')[0].value;
            var lname=document.getElementsByName('lname')[0].value;
            var email=document.getElementsByName('email')[0].value;
            var website=document.getElementsByName('website')[0].value;
            document.getElementsByName("test")[0].innerHTML = "First name: "+fname+"<br/>Last name: "+lname+"<br/>Email: "+email+"<br/>Website: "+website;
        }
    </script>
Try Yourself

In this method we target one or more HTML elements with their name attribute. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

Note: Name attribute’s value also can be accessible in the post method of server-side scripts like PHP. We will deal with it during the tutorials of server-side scripts.

How to target HTML Elements using the ‘querySelector’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelector('#test_id').innerHTML="This is First DIV Element.";
        document.querySelector('.test_class').innerHTML="This is Second DIV Element.";
    </script>
Try Yourself

In this method we target single HTML Element using CSS selector. In CSS if we want to target element with tag name we use the tag name, or if we want to use the ID or Class then we use ‘#’ with ID and ‘.’ with the class name. Similarly we can use CSS all selector to with query selector method.

Likewise ID case, it returns only the first node present on the web page.

How to target HTML Elements using ‘querySelectorAll’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelectorAll('#test_id')[0].innerHTML="This is First DIV Element.";
        document.querySelectorAll('.test_class')[0].innerHTML="This is Second DIV Element.";
        document.querySelectorAll('.test_class')[1].innerHTML="This is Third DIV Element.";
    
        console.log(document.querySelectorAll("DIV"));
    </script>
Try Yourself

This method is the same as the query selector method but in this method we target one or more HTML Elements using CSS selector and it returns a set the node list where each node can be accessed by the specific index number.

You have seen all the examples given above. These are the methods to target the HTML DOM or HTML DOMs in JavaScript. You must know a few things also which are mentioned below

  1. The methods that return the list of nodes can be looped. Check example 7 ahead.
  2. Although node list can be looped they aren’t referred to as an array because array must have few methods like push, splice & sort but not in case of node list.
  3. ID, Class, and Name are the attributes that can be directly accessed in JavaScript. For reference Check example 8.
  4. Id & name attribute can have one value at a time and can be used only once on the webpage but the class can have multiple values at the same time. The value should be separated by space. For e.g. class=”container box primary”. There are three different classes in the example container, box & primary.

How to apply loop on a NodeList?


Code Copied
<div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <script>
        var el=document.querySelectorAll('.test'),n=1;
        el.forEach(element => {
            element.innerHTML="This is DIV No. "+(n++);
        });
    </script>
Try Yourself

How to Find ID, Class & Name Attribute Values?


<div id="test_id">This DIV has id Attribute</div>
    <!--Class can have multiple value-->
    <div class="test_class1 test_class2 test_class3">This DIV has class Attribute</div>
    <div name="test_name">This DIV has name Attribute</div>


    <p id="result_1"></p>
    <p id="result_2"></p>
    <p id="result_3"></p>

    <script>
        document.getElementById("result_1").innerHTML = document.getElementById("test_id").id;
        document.getElementById("result_2").innerHTML = document.getElementsByClassName("test_class1")[0].className;
        document.getElementById("result_3").innerHTML = document.getElementsByName("test_name")[0].getAttribute("name");
    </script>
Try Yourself
progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

10 comments:

  1. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.

    PMP Certification in Malaysia
    PMP Certification

    ReplyDelete
    Replies
    1. Thank you, You valuable words of appreciation makes our enthusiasm high

      Delete
  2. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    data analytics course
    data science course
    big data course
    big data course
    360DigiTMG

    ReplyDelete
  3. They've managed the project exceptionally, especially in the face of scope changes.
    best service design company

    ReplyDelete
  4. Reliable, competent and responsive website designing and development company. This is how I revel in with it, and this is valid for both product and aid

    ReplyDelete
  5. Outstanding blog, in my opinion site owners should acquire a great deal out of this blog its very user welcoming.
    url opener extension for chrome

    ReplyDelete
  6. Their friendly customer service and attentive project management made the working relationship both informative and enjoyable.
    logo designing service

    ReplyDelete
  7. If you would like somebody that truly believes within the power associated with mobile app firm apparent personalization and somebody that invested the time into creating information that reflects your company intentions

    ReplyDelete
  8. Their design work was consistent from strategy to execution, like it was done by a single person
    brand management agency

    ReplyDelete