getElementsByName returns zero length in Javascript onload handler

139 Views Asked by At

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?

2

There are 2 best solutions below

2
Met Br On BEST ANSWER

As an alternative you can try tag name :

let items = document.getElementsByTagName("li");
0
cheesyMan On

Simply the getElementsByName() method is not the right one.

returns a NodeList Collection of elements with a given name attribute in the document.(https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName)

Here you don't have name attributes in your tags (li tags don't even accept name attributes)

What you need actually is the getElementsByTagName('li') method (https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName)

or the querySelectorAll('li') method (https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll)

The former gives you a live node collection, the latter a not-live node collection.