0
<li class="even">
<a href="www.google.com">Click here </a>
</li>

I want to change anchor tag text "Click here" using javascript. How can i accomplish this ?

2
  • No JQuery...so which browsers do you want to support? Commented May 20, 2011 at 4:03
  • you whant to do this directly on page load? or when its clicked or something Commented May 20, 2011 at 4:10

3 Answers 3

2

If you're not constrained to using that exact markup and you're really looking for one of the best ways to do this, start off by giving a unique Id to the element that you're going to change:

<a href="www.google.com" id="mylink">Click here</a>

document.getElementById("mylink") will give you that element.

Before manipulating an element on the page, you need to ensure that the document is loaded and ready for manipulation. Avoid using inline JavaScript in attributes. Use the following method to attach a document load handler:

window.onload = function () {
    // manipulate the document here
};

So, what you're looking for would be:

window.onload = function () {
    document.getElementById("mylink").innerHTML = "Something Else";
};

But, if you're really looking for a better solution, don't hesitate to enter the realm of jQuery:

$(function () {
    $("#mylink").html("Something Else");
});
Sign up to request clarification or add additional context in comments.

2 Comments

I would also note to only overwrite the window.onload if you are the only one working on that web page. The last person to do that wins. All other works will not show up. There are examples of how to work around that on this site. You just have to search.
@John: Well said. Another reason to use jQuery which silently handles that problem for you.
1
document.getElementsByTagName("a")[0].innerHTML = "Changed click here"; //0 is assuming this is your only link

It'd be better to use an id to access that particular link.

EDIT: I noticed you want this to happen on page load:

<body onload="document.getElementsbyTagName('a')[0].innerHTML = 'Changed text';">

Or you could placed that code in a function somewhere and call the function instead.

Comments

0
<body onload="document.getElementById('mylink').innerHTML='new text';">
    <li class="even">
        <a id='mylink' href="www.google.com">Click here </a>
    </li>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.