I can’t understand this code
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<button onclick="displayDate1()">The time is?</button>
<button onclick="displayDate2()">The time is?</button>
<script>
function displayDate() {
var x = document.querySelectorAll("p").length;
document.getElementById("d").innerHTML = x;
}
function displayDate1() {
var x = document.getElementsByClassName("d").length;
document.getElementsByClassName("a").innerHTML = x;
}
function displayDate2() {
var x = document.getElementsByTagName("p").length;
document.querySelectorAll("p").innerHTML = x;
}
</script>
<p id="d"></p>
<p class="a"></p>
<p></p>
</body>
</html>
The first function returns the length of the id element, but the other functions do not return the length of the element that I point to in the HTML document.
>Solution :
The problem is when you’re displaying the result rather than getting the length.
In the first function, you assign to document.getElementById(...)‘s innerHTML and that is fine, since getElementById returns a single element.
However, in the other functions, you assign to document.getElementsByClassName(...) and document.querySelectorAll(...) ‘s innerHTML, but those return NodeList and HTMLCollection, not a single element.
To solve this, choose a single element from the list/collection to assign to.