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 J开发者_开发百科S not work at all but the jQuery text()
works just fine?
Fiddle
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/
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
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).
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.
精彩评论