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
4 Answers
Reset to default 3To 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
版权声明:本文标题:html - Change anchor text with JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745409593a2657404.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论