0

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.

Artis84
  • 3
  • 3
  • 1
    `GetElementById` returns a single element, allowing you to set the `innerHTML` on the element directly. But `getElementsByClassName` and `querySelectorAll` both return *collections* of elements ([`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) and [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) respectively) which you can't set the `innerHTML` on directly, you would need to access one of the contained elements and set the innerHTML on that. – pilchard Aug 28 '22 at 09:09

1 Answers1

0

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.

Joachim
  • 71
  • 5