Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

length property of an html element

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading