简体   繁体   中英

javascript use for getting element

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

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");
});
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM