Travis
Travis

Reputation: 111

Change anchor text with JavaScript

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

Upvotes: 0

Views: 6715

Answers (4)

adam
adam

Reputation: 238

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

Upvotes: 0

Howard Renollet
Howard Renollet

Reputation: 4739

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.net/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>

Upvotes: 3

mdevils
mdevils

Reputation: 136

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.org/en-US/docs/Web/API/document.getElementsByClassName

Upvotes: 0

Nope
Nope

Reputation: 22339

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

Upvotes: 1

Related Questions