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
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
- 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: stackoverflow./questions/38093760/… What you can do is declare a Ref array and then loop over it – Shubham Khatri Commented Jun 25, 2017 at 19:13
1 Answer
Reset to default 3You need to run your code on ponentDidMount. You also need to get ul
first.
class MyComponent extends React.Component {
ponentDidMount() {
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 remend taking a look at querySelector and querySelectorAll since they might be useful.