Mike Fielden
Mike Fielden

Reputation: 10153

HTML5 'time' tag not setting value properly

I have the following code:

<html>
<script>


setInterval("settime()", 1000);

function settime () {
  var dateTime = new Date();
  var hours = dateTime.getHours();
  var minutes = dateTime.getMinutes();
  var time = "";

  if (hours === 0) { 
    hours = 12;
  }

  time = (hours > 12 ? hours - 12 : hours) + ":" +
         (minutes < 10 ? "0" : "") + minutes + (hours > 12 ? "PM" : "AM");

  // Doesn't work at all...
  document.getElementsByTagName('time').textContent = time;
  document.getElementsByTagName('time').innerHTML = time;


  console.log('Time set with js: ' + document.getElementsByTagName('time').textContent);

  // Works fine...
    //$('time').text(time);
}
</script>

<body>

    <time></time>

</body>
</html>

Why does the regular JS not work at all but the jQuery text() works just fine?

Fiddle

Upvotes: 2

Views: 1018

Answers (4)

amosrivera
amosrivera

Reputation: 26514

Because document.getElementsByTagName returns a nodeList and not a single element, you have to specify which. Node lists work like arrays so doing:

document.getElementsByTagName('time')[0].innerHTML = time;

works.

http://jsfiddle.net/4EqxW/3/

Upvotes: 3

Timothy Khouri
Timothy Khouri

Reputation: 31845

Marek Sebera and "amosrivera" answered the first part of your question (the main part)

And then to answer the second part of your question...

jQuery's "text()" method will perform the desired result on ALL of the elements that match your original selector (aka... every "time" element on the page).

Upvotes: 1

Kevin Ji
Kevin Ji

Reputation: 10489

Try

document.getElementsByTagName('time')[0].textContent = time;
document.getElementsByTagName('time')[0].innerHTML = time;

Note that getElementsByTagName returns a NodeList, which is an array, not a single element. Results of code change.

Upvotes: 0

Marek Sebera
Marek Sebera

Reputation: 40621

Note the document.getElementsByTagName('time')[0]. part

http://jsfiddle.net/4EqxW/4/

getElementsbyTagName is returning array of Nodes (NodeList) so you have to specifiy to which element you're accesing properties

Upvotes: 1

Related Questions