I have an HTML page with this block below. I cannot change it.
In JavaScript, I want to find all these a elements of class language-link and get their hreflang attribute, so I did this
var lang_links = document.getElementsByClassName('language-link');
for (var i = 0; i < lang_links.length; i++) {
console.log(lang_links[i].getAttribute('hreflang'));
}
But for some reason, this doesn't print anything. I found out that lang_links.length is equal to 0. If I add the two console.log before the for loop like so,
var lang_links = document.getElementsByClassName('language-link');
console.log(lang_links);
console.log("length: " + lang_links.length);
for (var i = 0; i < lang_links.length; i++) {
console.log(lang_links[i].getAttribute('hreflang'));
}
<nav class="links nav links-inline">
<span hreflang="en" class="en nav-link is-active">
<a href="/drupal/en" class="language-link is-active" hreflang="en">English</a>
</span>
<span hreflang="fr" class="fr nav-link">
<a href="/drupal/fr" class="language-link" hreflang="fr">French</a>
</span>
<span hreflang="ar" class="ar nav-link">
<a href="/drupal/ar" class="language-link" hreflang="ar">Arabic</a>
</span>
</nav>
my browser's console prints
HTMLCollection []
> 0: a.language-link.is-active
> 1: a.language-link
> 2: a.language-link
length: 3
> __proto__: HTMLCollection
length: 0
How does the array get printed correctly, even telling me the correct length, but when I print the array's length it says 0?
Also, if I run my code in the browser's console, I get the expected output that shows all hreflang attributes:
HTMLCollection(3) [a.language-link.is-active, a.language-link, a.language-link]
> 0: a.language-link.is-active
> 1: a.language-link
> 2: a.language-link
length: 3
> __proto__: HTMLCollection
length: 3
en
fr
ar
Is it possibly due to the JavaScript code running before the elements get created? But if that was the case, console.log(lang_links) shouldn't have printed anything...
Edit: I am using Drupal 8, so I cannot change the script position in the HTML document (I think). I can't see my JavaScript files if I use the inspector, but it looks like Drupal runs scripts at the end of the body since this is where all scripts in the inspector appear and my others getElementByClassName() run with no problems.