Search code examples
javascripthtmlinnerhtml

Why does my innerHTML disappear when replacing it?


I'm trying to replace some HTML using .innerHTML and .replace.

From:

aaaaaa/cat/bbbbbb

To:

<a href="http://www.google.com/cat/world">Helloworld</a>

This is my code:

<body>
    <p id="element1">aaaaaa/cat/bbbbbb</p>

    <script language="javascript">
        var strMessage1 = document.getElementById("element1") ;
        strMessage1.innerHTML = strMessage1.innerHTML.replace( /aaaaaa./g,'<a href=\"http://www.google.com/') ;
        strMessage1.innerHTML = strMessage1.innerHTML.replace( /.bbbbbb/g,'/world\">Helloworld</a>') ;
    </script>
</body>

When I run this code it makes the Helloworld hyperlink disappear. What am I doing wrong?


Solution

  • You should chain the replace() together instead of assigning the result and replacing again.

    var strMessage1 = document.getElementById("element1") ;
    strMessage1.innerHTML = strMessage1.innerHTML
                            .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                            .replace(/.bbbbbb/g,'/world\">Helloworld</a>');
    

    See DEMO.