最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React equivalent of getElementsByTagName - Stack Overflow

programmeradmin0浏览0评论

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

Share Improve this question asked Jun 24, 2017 at 21:29 The WalrusThe Walrus 1,2087 gold badges31 silver badges50 bronze badges 1
  • 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
Add a ment  | 

1 Answer 1

Reset to default 3

You 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.

发布评论

评论列表(0)

  1. 暂无评论