We can use jQuery to change the id of a div by using the jQuery attr() method. To do this we can target the current id of the div, and then use the attr() method to then change the id.

$("#div1").attr("id","div2");

Let’s say I have the following HTML:

This is a paragraph.

If we want to change the div id from “div1” to “div2” we could use the jQuery attr() method to do this with the following JavaScript code.

$("#div1").attr("id","div2");

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").attr("id","div2");

Using jQuery to Change the Id of a Div With a Click

We can change the id of an HTML element using jQuery very easily by combining the attr() method with a click event.

In this example, we will have a paragraph with an id that has certain styles. We will replace that id with another id that has different styles. The HTML setup is pretty simple.

Here is the HTML code:


This is the paragraph that we can change the id of.

Change to id p2
Change to id p1

We can utilize both the jQuery click() method and the jQuery attr() method to change the id of the paragraph to either #p1 or #p2. If the paragraph has id “p1”, then it will have an underline style. If it has id “p2”, then it will be bold.

Below are the two functions that will allow the user to be able to change the id of the paragraph:

$("#click-me1").click(function(){
  $("#p1").attr("id","p2");
}); 
$("#click-me2").click(function(){
  $("#p2").attr("id","p1");
}); 

The final code and output for this example of using jQuery to change the id of a div with a click is below:

Code Output:

This is the paragraph that we can change the id of.

Change to id p2
Change to id p1

Full Code:


This is the paragraph that we can change the id of.

Change to id p2
Change to id p1

Hopefully this article has been useful for you to understand how to use jQuery to change the id of a div.

Categorized in:

jQuery,

Last Update: February 26, 2024