Javascript DOM How to - Change the ID of an HTML element








Question

We would like to know how to change the ID of an HTML element.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="foo"></div>
    <script type='text/javascript'>
    <!--   ww  w. j a v a 2 s  .co  m-->
        var obj = document.getElementById("foo");
        obj.id = "rar";
        console.log(obj.id);
        console.log(document.getElementById("rar").id);
    
    </script>
</body>
</html>

The code above is rendered as follows: