This is an example source.
<div ref={this.mainRef}> <div> <ul> <li role="option" id="1">A</li> <li role="option" id="2">B</li> <li role="option" id="3">C</li> <li role="option" id="4">A</li> <li role="option" id="5">B</li> <li role="option" id="6">C</li> </ul> </div> </div>
With this.mainRef
, how do I get the list of elements matching attribute of ‘role=option’?
Something like..
const selectableOptions = this.mainRef.children.search(role=option)
- I don’t want to go through the DOMs tree because the structure might get changed.
- I would like to “search” instead.
THANKS!
Advertisement
Answer
Please try below.
const divRef = useRef(null)
<div ref={divRef}> <div> <ul> <li role="option" id="1">A</li> <li role="option" id="2">B</li> <li role="option" id="3">C</li> <li role="option" id="4">A</li> <li role="option" id="5">B</li> <li role="option" id="6">C</li> </ul> </div> </div>
const matches = divRef.current.querySelectorAll("li[role='option']");