What is an ID?
The ID is an one of the attribute and we can assign IDname to all HTML elements using ‘ID’ attribute. It is used to give a unique identifier to an element on a webpage. It is similar to class attribute but in class attribute we can give multiple classnames but in ID attribute we can’t give. And we should give unique name to ID.
For example, the following HTML code defines a <p> element with the ID “myPara”:
<p id="myPara">Hello World!</p>
Why should we hide element by ID ?
- You may want to hide a navigation bar until the user clicks on a menu icon, or hide a pop-up message after the user has read it. So, it’s improve the visual appearance or functionality of the page.
- You can improve the performance of the web page by hiding the elements of unnecessary amount of code
- It’s used to prevent unauthorized access or to protect user privacy. For ex, you may want to hide a password input field as the user types in their password, or hide certain personal details until the user has logged in.
Why hide the element by id instead of class?
- IDs are meant to be unique identifiers whereas classes can be shared by multiple elements on a web page. So, we can use ID to hide elements because it ensures that you are targeting the correct element and not accidentally hiding other elements.
- When we hide an element by its ID, the browser can quickly locate the element using the built-in getElementById() function. Whereas if we use class to hide an element, this can be slower than searching for elements by ID.
However, if you need to hide multiple elements with the same style, hiding them by class may be more appropriate.
2 Methods to hide element by ID
1. getElementById method
var element = document.getElementById("section1"); element.style.display = "none";
In this above example code:
- In HTML code, we have created the <div> element and set the ID name to ‘section1’.
2. setAttribute Method
As we selected HTML element in previous method, in this method also select HTML element by id using getElementById() function. Then Use setAttribute() to hide the element.
var element = document.getElementById("section1"); element.setAttribute("style", "display: none;");
- In the above HTML code we have created a div element and set its idname to ‘section1’
- To hide an element, we need to use the ‘setAttribute()’ method and pass it two arguments “style” and “display: none;“. The first argument indicates the attribute name and second attribute indicates the attributevalues. The display property controls whether an element is visible or hidden on a webpage. If we set ‘none’ to display property, it shows nothing.
- This code will store in HTML code by CSS inline style like:
<div style="display: none;" id="section1"><h1>Footer</h1></div>