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

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:

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

<?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");
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