aliali aliali - 10 months ago 36
Javascript Question

Replace link and word with JavaScript

I have

<a target="_blank" href="" id="name">good</a>

in my website.

How can I replace

    , and

  • good

by using JavaScript?

I tried this:

function myFunction() {
var str = document.getElementById("name").innerHTML;
var res = str.replace("good", "bad");
document.getElementById("name").innerHTML = res;


You are using JavaScript which is very distinct from Java. Your function seems to be over-complicating things a bit. You can simply do this:

function myFunction() {
    document.getElementById('name').innerText = 'bad';

Note: innerText is safer than innerHTML.

For the link you can independently do this:

function myLinkFunction() {
    document.getElementById('name').href = '';

Or you can combine the functions like this:

function myFunction() {
    var elem = document.getElementById('name');
    elem.innerText = 'bad';
    elem.href = '';

Of course you'll still have to call your function (myFunction();) which you can do in an event handler like this:

<button onClick='myFunction();'>Change link</button>