How to usethe id property with inline onclick function in Javascript

Using JavaScript, we can use the id property inside the element to change the ID.

Example:  In this example, we will use the id property for changing the id.

html




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>
          How to change the ID of element using JavaScript ?
    </title>
    <style>
        .div {
            height: 100px;
            width: 200px;
            margin: 0 auto;
            color: white;
        }
     
        #div1 {
            background: green;
        }
     
        #div2 {
            background: blue;
        }
    </style>
</head>
<body style="text-align:center;">
     
        <h1 style="color:green;">
            w3wiki
        </h1>
     
        <p id="GFG_UP"></p>
     
        <div class="div" id="div1"></div>
        <br>
     
        <button onclick="document.getElementById(
            'div1').id = 'div2'; return false">
            click here
        </button>
     
        <script>
            let el_up =
                document.getElementById('GFG_UP');
 
            el_up.innerHTML = "Click on button to"
                + " change the ID of box.";
        </script>
</body>
</html>


Output:



How to change the ID of element using JavaScript ?

In this article, we will learn how to change the ID of elements using JavaScript. ID is unique for any element and it can be assigned to an element only once. JavaScript provides a method to access this id and also to manipulate the id. 

Syntax:

Selected_element.id = newID;

There are two approaches that are discussed below:

Table of Content

  • Using the id property
  • Using the id property with inline onclick function

Similar Reads

Approach 1: Using the id property

We can use the id property to change the ID using JavaScript....

Approach 2: Using the id property with inline onclick function

...