admin管理员组文章数量:1287774
Trying to inject a dynamic year into HTML code.
Works fine with getElementById but getElementsByClassName doesn't seem to be working.
Here is my code...
HTML
<p>this year is <span class="year"></span></p>
JAVASCRIPT
document.getElementsByClassName("year").innerHTML = new Date().getFullYear();
Interested to see what I am doing wrong.
Trying to inject a dynamic year into HTML code.
Works fine with getElementById but getElementsByClassName doesn't seem to be working.
Here is my code...
HTML
<p>this year is <span class="year"></span></p>
JAVASCRIPT
document.getElementsByClassName("year").innerHTML = new Date().getFullYear();
Interested to see what I am doing wrong.
Share Improve this question asked Feb 20, 2015 at 14:57 AdamAdam 1,4598 gold badges29 silver badges48 bronze badges 1-
2
document.getElementsByClassName("year")[0]
, because it's an array, you need to select the first one. – blex Commented Feb 20, 2015 at 14:58
2 Answers
Reset to default 8You get an array of elements with this method. To access the first element write this:
document.getElementsByClassName("year")[0].innerHTML = new Date().getFullYear();
The getElementsByClassName
function returns a HTMLCollection
object.
You can access each element in the collection with the same syntax as an array :
var yearCollection = document.getElementsByClassName("year");
yearCollection[0].innerHTML = new Date().getFullYear();
You can also use querySelector
and querySelectorAll
to retrieve elements.
Using querySelector the result is more readable in my opinion :
document.querySelector(".year").innerHTML = new Date().getFullYear();
querySelector
and querySelectorAll
use CSS selectors to get element in the DOM.
For a quick perf parison see : http://jsperf./selection-amdg2-azfne65
本文标签: javascriptTrying to get element by className doesn39t seem to be workingStack Overflow
版权声明:本文标题:javascript - Trying to get element by className doesn't seem to be working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741318325a2372054.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论