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.
Table of Contents
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.