getelementsbyname

why document.getElementsByName().length always return 0?


I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many <li>-tags in my HTML, why?

document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('li').length;
    alert(len);
})

art of my HTML:

<body>
    <ul>
        <li>aaaaaa</li>
        <li>bbbbbb</li>
        <li>cccccc</li>
    </ul>
</body>

Solution

  • Replace

    document.getElementsByName('li')

    with

    document.getElementsByTagName('li')

    This is happening cause you are selecting by tag name and not by name ! You are using wrong function!