Finding child element of parent pure javascript

后端 未结 4 1125
逝去的感伤
逝去的感伤 2020-12-02 06:48

What would the most efficient method be to find a child element of (with class or ID) of a particular parent element using pure javascript only. No jQuery or other framework

4条回答
  •  悲哀的现实
    2020-12-02 07:24

    The children property returns an array of elements, like so:

    parent = document.querySelector('.parent');
    children = parent.children; // [
    ]

    There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


    Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

    children = document.querySelectorAll('.parent .child1');
    

    The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

提交回复
热议问题