Change id of Element JavaScript

In this tutorial we will learn how to Change id of Element with JavaScript. HTML DOM Element id Property and setAttribute() method both can be used to change the id of any HTML tag or element.

id property

id property sets or returns the id of the HTML tag.

In this example we can use id property to change the id of HTML element.

setAttribute() method

setAttribute() method sets the new value of the defined attribute of HTML tag.

In this example setAttribute() method can be used to change the value id attribute.

getElementById() method

getElementById() method selects or targets the HTML element based on it's id.

In this example getElementById() method is used to select the p tag by it's id.

HTML Code

HTML Code is given below, in this code we have a p tag and a button tag.

<!DOCTYPE html>
<html>
<head>
<title>Change id of Element with JavaScript</title>
<style>
#red
{
color: red;
}
#blue
{
color: blue;
}
</style>    
</head>             
<body>

<p id="red">This is HowToCodeSchool.com</p>
<button onclick="changeId()">Change id</button>    
    
<script src="script.js"></script>    
</body>
</html>

JavaScript Code

Take a look at the JavaScript code, In this code getElementById() method is used to select p tag and id property is used to change the id of p tag.

Since both new and old ids are used to define different text color of p tag in CSS, the change of id would be visible.

<script>
function changeId()
{
    var element = document.getElementById('red');
    element.id = 'blue';
}
</script>

Same example with setAttribute() method.

<script>
function changeId()
{
    var element = document.getElementById('red');
    element.setAttribute('id','blue');
}
</script>

Demo

Video Tutorial

Watch video tutorial on How To Change id of HTML tag using JavaScript.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color