When I started working with HTML, I was confused about the id attribute and the class attribute of an element. I didn’t know the differences between them so I used them arbitrarily. After some small projects, I have realized their differences and how to use them more correctly.
Let’s see the definition of those attributes:
The
classattribute specifies one or more classnames for an element.The
http://www.w3schools.comidattribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
The first difference between two attributes is many elements can have the same class but the id must belongs to only one element. Let’s see the code below:
<div class="block">
<h2 id="title">This is the title</h2>
<p>This is the paragraph underneath the title</p>
</div>
<div class="block">
<p id="content">This paragraph contains characters</p>
</div>
Two div element share the same class, it’s ok. The h2 element has title id and the second p element has content id, those ids are unique and only belong to one element. So what happens if there are two elements have the same id? Let’s check the code:
<button id="btn">Say</button>
<button id="btn">Talk</button>
document.getElementById("btn").onclick = () => {
console.log("hi!");
}
Two button have the same btn id, when user click on the button has the btn id, the browser will say “hi!”. With the first button, it works fine. But the second button does nothing. That because HTML only accepts one element has the btn id and if there are more elements have that id, HTML only recognizes the first one.
Elements can share the class attribute so when you use the code below, you will get an array of elements using that class:
let els = document.getElementsByClassName("block");
//els is an array
When you want to work with a specific element in the array, you have to use the array index:
els[0]; //for the first one
els[1]; //for the second one
If you don’t use the index, all of the elements in the array will be effected.
els.onclick = () => {
console.log("Bye");
}
//everytimes the elements using the "block" class are clicked, the browser say "Bye"
Conclusion
Use class for reusable code because it can be shared with many elements, you can save many of coding time and your project can be maintainable.
For specific element has some special behaviors belonging to only this element, use id.
Bình luận về bài viết này