javascriptgetelementsbyname

getElementsByName returns zero length in Javascript onload handler


This question is about HTML with pure JavaScript (no jQuery or further technology).

I try to write by hand a file with a list of URLs which should appear as links. To reduce typing and avoid inconsistencies, I want to use JavaScript to take a list of li elements and translate it into li elements containing appropriate a elements with the URLs as href and as text.

Working in this direction, I have arrived at the following code, a bit condensed (no a elements) to show the issue at hand:

<?xml version="1.0" encoding="UTF-8"?>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body onload="linkify()">
<ul>
    <li href="https://stackoverflow.com/questions/5844732/getelementsbytagname-length-returns-zero" />
    <li href="https://stackoverflow.com/questions/26932862/why-does-document-getelementsbyname-have-a-length-of-0-despite-having-elements" />
    <li href="https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects" />
</ul>
<script>
function linkify () {
    let items = document.getElementsByName( "li" );
    for ( let i = 0; i < items.length; ++i ) {
        item = items.item( i );
        item.innerHTML = item.getAttribute( "href" );
    }
}
</script>
</body>
</html>

I expect the page to show a list of URLs. However, the list remains three empty list items, no URLs. The debugger tells me that let items = document.getElementsByName( "li" ); gets a 0 items.length object so that the for-loop does not do anything.

I would expect that linkify() is only called when the whole DOM has been loaded, so all three li elements should be found. Where is my error?


Solution

  • As an alternative you can try tag name :

    let items = document.getElementsByTagName("li");