admin管理员组

文章数量:1424948

I'm trying to change the text of an anchor tag. I've done this before by targeting the DIV it is in and then targeting the anchor tag within that DIV. But without any div or assigned ID on the anchor tag I'm lost. Here is what I have so far:

HTML:

<a href="#" class="small quality hide-forsmall" >Link Text</a>

JavaScript:

var anchor=document.getElementsByClassName("quality");
anchor.innerHTML="Changed Text";

I'm trying to change the text of an anchor tag. I've done this before by targeting the DIV it is in and then targeting the anchor tag within that DIV. But without any div or assigned ID on the anchor tag I'm lost. Here is what I have so far:

HTML:

<a href="#" class="small quality hide-forsmall" >Link Text</a>

JavaScript:

var anchor=document.getElementsByClassName("quality");
anchor.innerHTML="Changed Text";
Share Improve this question edited Dec 5, 2013 at 20:50 Jasper 76k14 gold badges152 silver badges148 bronze badges asked Dec 5, 2013 at 20:48 TravisTravis 1111 gold badge2 silver badges5 bronze badges 2
  • 1 Try var anchor=document.getElementsByClassName("quality")[0] – Comfortably Numb Commented Dec 5, 2013 at 20:50
  • When should the code run? – Jasper Commented Dec 5, 2013 at 20:50
Add a ment  | 

4 Answers 4

Reset to default 3

To get each of the elements with that specific class name, you need to loop through the collection. Here is a quick example:

http://jsfiddle/QU7Kv/1/

<a href="#" class="small quality hide-forsmall" >Link Text</a>


<script>
    (function (){
        var anchor=document.getElementsByClassName("quality");
        for(var i = 0; i < anchor.length; i++){
            anchor[i].innerHTML="Changed Text";
        };
     })()
</script>

document.getElementsByClassName returns a HtmlCollection of elements matching the class name.

To get the first one use:

document.getElementsByClassName("quality")[0];

To change the text in all matching elements, iterate over them, similar to:

for(var i = 0; i < anchor.length; i++){
    anchor[i].innerHTML="Changed Text";
}

Alternatively you can also use querySelector() which will return the first match only and therefor returns a single element only, similar to:

var anchor=document.querySelector(".quality");
document.getElementsByClassName("quality");

Method getElementsByClassName returns HTMLCollection, not a single node. If you want to access the first result, try this:

var anchor = document.getElementsByClassName("quality")[0];
anchor.innerHTML = "Changed Text";

More info about getElementsByClassName: https://developer.mozilla/en-US/docs/Web/API/document.getElementsByClassName

getElementsByClassName returns HTMLCollection. Please refer to https://developer.mozilla/en-US/docs/Web/API/document.getElementsByClassName.

本文标签: htmlChange anchor text with JavaScriptStack Overflow