Reputation: 10153
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?
Upvotes: 2
Views: 1018
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.
Upvotes: 3
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
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
Reputation: 40621
Note the document.getElementsByTagName('time')[0].
part
getElementsbyTagName
is returning array of Nodes (NodeList) so you have to specifiy to which element you're accesing properties
Upvotes: 1