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>
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>
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>
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>
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>
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>
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
- The methods that return the list of nodes can be looped. Check example 7 ahead.
- 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.
- ID, Class, and Name are the attributes that can be directly accessed in JavaScript. For reference Check example 8.
- 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?
<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>
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>
Thank you, You valuable words of appreciation makes our enthusiasm high
ReplyDeleteThumbs up guys your doing a really good job.
ReplyDeletedata science course in malaysia
They've managed the project exceptionally, especially in the face of scope changes.
ReplyDeletebest service design company
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
ReplyDeleteOutstanding blog, in my opinion site owners should acquire a great deal out of this blog its very user welcoming.
ReplyDeleteurl opener extension for chrome
Their friendly customer service and attentive project management made the working relationship both informative and enjoyable.
ReplyDeletelogo designing service
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
ReplyDeleteTheir design work was consistent from strategy to execution, like it was done by a single person
ReplyDeletebrand management agency
It’s amazing in support of me to truly have a blog site, which will be valuable meant for my knowledge. Thanks admin.
ReplyDeletebest UX companies
I am sure that this is going to help a lot of individuals. Keep up the good work. It is highly convincing and I enjoyed going through the entire blog.
ReplyDeletedata science course
It’s my fortune to go to at this blog and realize out my required stuff that is also in the quality.
ReplyDeleteprofessional logo design service
The vital information in this blogs has allured me.
ReplyDeletebest web design agency
The stuff in this blog is in not only incredible but also providing the great knowledge to the people.
ReplyDeletedigital design agency
I will prefer this blog because it has much more informative stuff.
ReplyDeleteexperience design agency