Skip to content

JavaScript replace HTML tags | Replace RegEx example

  • by

How to Replace particular html tags using JavaScript?

Frist get tags you want to replace then replace old HTML with new HTML. You have to use innerHTML, replace method, and regex (regular expression) to replacing HTML tags using JavaScript.

JavaScript replace HTML tags example code

Let’s see example code with 2 scenarios first if only want signal tag and second is if want all tags.

Replace single Tag

For a single-element tag change, you have to create a new element and move the contents into it. Example:

<!DOCTYPE html>
<html>
<body>
    <span> Hello World</span>
    <span class ="ch"> How are you?</span>
    <p> This tag nog change</p>

    <script type="text/javascript">

        var e = document.getElementsByTagName('span')[0];

        var d = document.createElement('div');
        d.innerHTML = e.innerHTML;

        e.parentNode.replaceChild(d, e);

    </script>

</body>

</html>

Output:

JavaScript replace HTML tags

Replace all tag

It’s easy to change all tags, for example changing the span tag with div tag.

<!DOCTYPE html>

<!DOCTYPE html>
<html>
<body>
    <span> Hello World</span>
    <span> How are you?</span>
    <p> This tag nog change</p>

    <script type="text/javascript">

        var elems = document.getElementsByTagName('body')[0];

        
        var target = elems.innerHTML;
        elems.innerHTML = target.replace(/(<span)/igm, '<div').replace(/<\/span>/igm, '</div>');

    </script>

</body>

</html>

Output:

JavaScript replace HTML tags all

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

Discover more from Tutorial

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

Continue reading