Change element tag name JavaScript | Using Pure JS Example

To change the element tag name in JavaScript, simply need to make a new element and move over all the elements so you keep onclick handlers and such, and then replace the original thing.

Example of replacing specific tag name JavaScript

Complete HTML example code:-

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        p { background-color:green;color:white; }
        div { background-color:blue;color:white; }
    </style>

    <script>


      function replaceTag(id){
       var that = document.getElementById(id);

       var p = document.createElement('p');
       p.setAttribute('id',that.getAttribute('id'));

     // move all elements in the other container.
     while(that.firstChild) {
         p.appendChild(that.firstChild);
     }
     that.parentNode.replaceChild(p,that);

 }
</script> 
</head>
<body>

    <div id="demo">Hello WORLD
     <UL>
      <LI>something</LI>
  </UL>
</div>

<input type="button" onclick="replaceTag('demo')" value="transform">


</body>
</html>

Code source: stackoverflow.com

Output:

replace specific tag name JavaScript

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.