4

I am trying to get this var li = ul.getElementsByTagName('li'); to work in React however it is returning null as I guess the dom hasn't fully loaded. so Im looking for the reacty way to do this or a way to not get it to run until the dom has loaded

The Walrus
  • 1,148
  • 6
  • 28
  • 46
  • Unfortunately React doesn't provide an method to access all the elements by a Tag name as yet(v15.5.4) . However keeping this answer as a reference: https://stackoverflow.com/questions/38093760/in-react-js-is-there-any-function-similar-like-document-getelementbyid-in-javascript What you can do is declare a Ref array and then loop over it – Shubham Khatri Jun 25 '17 at 19:13

1 Answers1

3

You need to run your code on componentDidMount. You also need to get ul first.

class MyComponent extends React.Component {
    componentDidMount() {
        let ul = document.getElementsByTagName('ul')[0];
        let li = ul.getElementsByTagName('li');
        console.log(li); // you should have an array with list items inside an specific unordered list
    }
    render() {
        return (
            <ul>
                <li>item1</li>
                <li>item2</li>
                <li>item3</li>
            </ul>
        )
    }
}

I would recommend taking a look at querySelector and querySelectorAll since they might be useful.

Tiago Alves
  • 2,290
  • 13
  • 32