I'm trying to replace html using innerHTML javascript.
From:
aaaaaa/cat/bbbbbb
To:
<a href="http://www.google.com/cat/world">Helloworld</a>
This's my code
<html>
<head>
</head>
<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>
</html>
When i run this code it disappears Helloworld hyperlink. what I'm doing wrong. Please help.
Thank you for all your help.
For replacing innerHTML of a div with jquery, html() function is used. After loading the web page, on clicking the button content inside the div will be replaced by the content given inside the html() function.
To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
Simple find and replace of text in HTML The same can be done with Ctrl+C (copy) and Ctrl+V (paste). Then add replacement text (4) or leave it empty if you want to delete given text occurrences from HTML. Click Add button (5).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With