We can use jQuery to remove the id of a div by using the jQuery removeAttr() method.
$("#div1").removeAttr("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 removeAttr() method.
$("#div1").removeAttr("id");
The resulting HTML would be as follows:
This is a paragraph.
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").removeAttr("id");
Using jQuery to Remove the Id of a Div With a Click
We can remove the id of an HTML element using jQuery very easily by combining the removeAttr() 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
We can utilize both the jQuery click() method and the jQuery removeAttr() 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 using the attr() method.
Here is the JavaScript code below:
$("#click-me1").click(function(){
$("#p1").removeAttr("id");
});
$("#click-me2").click(function(){
$("#div1 p").attr("id","p1");
});
The final code and output for this example of using jQuery 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
Hopefully this article has been useful for you to understand how to use jQuery to remove the id of a div.