aliali aliali - 7 months ago 14
Javascript Question

Replace link and word with JavaScript

I have

<a target="_blank" href="http://www.bbb.com" id="name">good</a>


in my website.

How can I replace


  • http://www.bbb.com
    with
    http://www.eee.com
    , and

  • good
    with
    bad



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;
}

Answer

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 = 'http://eee.com';
}

Or you can combine the functions like this:

function myFunction() {
    var elem = document.getElementById('name');
    elem.innerText = 'bad';
    elem.href = 'http://eee.com';
}

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>
Comments