To change the id of an element in JavaScript we can do this by combining the getElementById() method along with the id property.

document.getElementById("div1").id = "div2";

Let’s say I have the following HTML:

This is a paragraph.


If we want to change the id of the div from “div1” to “div2” we could use the id property to do this with the following JavaScript code.

document.getElementById("div1").id = "div2";

The resulting HTML would be as follows:

This is a paragraph.


How to Change the Id of an Element in JavaScript With a Click

We can change the id of an HTML element using JavaScript very easily by combining the id property with an onclick 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 id property and the getElementById() 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.

We will use two onclick events that will run either function we create below. We will put the code above in our functions to allow the user to be able to change the id of the paragraph

Here is the JavaScript code:

function changeId1(){
  document.getElementById("p1").id = "p2";
}; 
function changeId2(){
  document.getElementById("p2").id = "p1";
}; 

The final code and output for this example of using JavaScript 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 change the id of an element in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024