Search code examples
javascripthtmlreactjstabshtmlcollection

Getting null when accessing to HTMLcollection


I have 4 tabs with a list in order to give them the title. I want to access the titles of each tab, but I can only access the whole HTMLcollection. Using react.

import React from 'react';
import {Component} from 'react';

class tabs extends Component {

    render() {
        return (
            <div className={"tabs"}>
                <ul>
                    <li><a>Class 1</a></li>
                    <li><a>Class 2</a></li>
                    <li><a>Class 3</a></li>
                    <li><a>Class 4</a></li>
                </ul>

                {console.log(document.getElementsByTagName("li"))};
                //full collection with length of 4

                 {console.log(document.getElementsByTagName("li").length)};
                 //0


       {console.log(document.getElementsByTagName("li").item(0).innerHTML)};
                  //"Cannot read property 'innerHTML' of null"

            </div>
        )
    }
}

export default tabs;

Solution

  • That's because when you declare JSX it doesn't immediately get printed into DOM. First, it will be transpiled by Babel and after the render hook React will update the DOM. But hey, in a middle of that you tried to already access these DOM elements...