Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Replace html using innerHTML

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.

like image 513
Dexter Avatar asked Mar 25 '13 15:03

Dexter


People also ask

What is the replacement of innerHTML in JavaScript?

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.

How do I change the content of innerHTML of HTML elements?

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.

Why you should not use innerHTML in JavaScript?

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.

How do you replace content in HTML?

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).


1 Answers

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.

like image 74
Antony Avatar answered Sep 28 '22 06:09

Antony