Javascript - Replace html using innerHTML

前端 未结 2 1787
-上瘾入骨i
-上瘾入骨i 2020-12-16 14:28

I\'m trying to replace html using innerHTML javascript.

From:

aaaaaa/cat/bbbbbb

To:



        
相关标签:
2条回答
  • 2020-12-16 15:19

    You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

    var html = strMessage1.innerHTML;
    html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
    html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
    strMessage1.innerHTML = html;
    
    0 讨论(0)
  • 2020-12-16 15:23

    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.

    0 讨论(0)
提交回复
热议问题