HelloWorldNoMore
HelloWorldNoMore

Reputation: 317

Cannot detect element by classname

I am a beginner and I am using pure javascript for DOM manipulation. I am not able to get all the divs in my section element. I get undefined. Please tell me what is the error and how I can fix it.

HTML

    <section class="main-content">
        <aside>
            <p>
                <span class="sidebartext">Watch this space for breaking news items.</span>
            </p>
        </aside>

        <section class="notes">
            <div id="Services" class="nav-pages active">Services</div>
            <div id="Resources" class="nav-pages">Resources</div>
            <div id="Contact-Us" class="nav-pages">Contact Us</div>
            <div id="Company" class="nav-pages">Company</div>
        </section>

    </section>

JS

var navTabs = document.getElementsByClassName('notes').children;
console.log(navTabs);//undefined

No jQuery answers please !!!

Upvotes: 2

Views: 1559

Answers (2)

Mehdi
Mehdi

Reputation: 418

That happens because getElementsByClassName returns an HTMLCollection or NodeList. If you console log just that element, "notes" you will see why you are getting an undefined.

Replace your JS code by:

var navTabs = document.getElementsByClassName('notes');
console.log(navTabs);

That will output an array which once expanded, it will show the content of the position [0]. If you expand that one you will get your NodeList labeled as childNodes. Expand it and you will get your divs.

Try this to get directly your divs:

console.log('Items: ',navTabs[0].childNodes);

Upvotes: 0

Dominic K
Dominic K

Reputation: 7075

getElementsByClassName returns an array of elements (actually, array-like - see @Hamms comment below), so children is undefined on it. If there's only one notes section, you can choose to use id="notes" instead (with getElementById) or iterate through the above array and access children from that.

Upvotes: 8

Related Questions