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
Add a ment  | 

2 Answers 2

Reset to default 8

You 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