javascript HTMLCollection access

children, htmlcollection, javascript

Solution

The element can only be found after the HTML page has been constructed. If your piece of code is standalone in a `<script>` in the document `<head>`, there is no element of class `"active"` yet.

Place your code in `windows.onload`, which is called after the page has been loaded and its elements created:

window.onload = function() {
    var SelectedItem = document.getElementsByClassName("active");

    console.log(SelectedItem);
    console.log(SelectedItem.length);
} 

Then your collection should have a length of 1 and you can access the first element with `[0]`. The code will also work when evoked from event handlers like `onclick`, which will only fire if the document is there already. (Because otherwise there wouödn't be any button to click.)

Problem

I made a website and need to impelment javascript. I would like to get the child nodes from my HTML menu. Here is a part of my HTML structure: ``` <ul class="menu"> <div class="moduletable_menu"> <ul class="nav menu nav-pills"> <li class="item-101"> <li class="item-108 current active deeper parent"> <li class="item-127"> <li class="item-113 deeper parent"> <li class="item-124"> <li class="item-116 deeper parent"> </ul> </div> </ul> ``` So, I would like to get the "active" element. I made the following code: ``` function getmenuItem(){ var SelectedItem = document.getElementsByClassName("active"); console.log(SelectedItem); console.log(SelectedItem.length); } ``` Here comes the problem: I displayed the console via Firebug and it showed me ``` HTMLCollection[] 0 ``` Then I tried to access the Collection with `SelectedElement[0]` but I got "undefined". Please show me how to get the children of the active element.

Original source