We can use JavaScript to remove the id of a div by using the removeAttribute() method.
document.getElementById("div1").removeAttribute("id");
Let’s say I have the following HTML:
This is a paragraph.
If we want to remove the id of div “div1” in the HTML above, we can target that div and then use the removeAttribute() method.
document.getElementById("div1").removeAttribute("id");
The resulting HTML would be as follows:
This is a paragraph.
Using JavaScript to Remove the Id of an Div With a Click
We can remove the id of an HTML div using JavaScript very easily by combining the removeAttribute() method with a click event.
In this example, we will have a paragraph with a bold and underlined style. We will then remove the id of the paragraph so that it will have no styles. The HTML setup is pretty simple.
Here is the HTML code:
This is the paragraph that we can remove the id of.
Remove id p1
Set id p1
We can utilize both the onclick event and the removeAttribute() method to remove the id of the paragraph #p1. If the paragraph has id “p1”, then it will have an underline and bold style. When we remove this id, it will have none of these styles.
Below are the two functions that will allow the user to be able to set or remove the id of the paragraph. We can set the id of an element too back to p1.
Here is the JavaScript code below:
function removeId1(){
document.getElementById("p1").removeAttribute("id");
};
function setId1(){
document.querySelector("#div1 p").id = "p1";
};
The final code and output for this example of using JavaScript to remove the id of a div with a click is below:
Code Output:
This is the paragraph that we can remove the id of.
Full Code:
This is the paragraph that we can remove the id of.
Remove id p1
Set id p1
Hopefully this article has been useful for you to understand how to use JavaScript to remove the id from a div.