Skip to content

Change tag using JavaScript | Span to div example code

How can I change a tag with pure JavaScript like that?

<span>some text</span>

change span tag to div tag etc.

<div>some text</div>

Example how to Change tag using JavaScript

Use innerHTML and replace the method with a regular expression to change the tag name JS.

<!DOCTYPE html>
<html>
<body>
 
    <span class="span1"> Text in span</span>
 
    <script type="text/javascript">
 
        var elem = document.getElementsByTagName('body')[0];
        var target = elem.innerHTML;
        
        console.log(target);
 
        elem.innerHTML = target.replace(/(<span)/igm, '<div').replace(/<\/span>/igm, '</div>');
    </script>
</body>
 
</html>

Output:

Change tag using JavaScript

Do comment if you have another example or way to do it. You can also do comment if have any suggestions or doubts 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

1 thought on “Change tag using JavaScript | Span to div example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading