Here's the sample html:
<div aria-atomic="true" aria-live="polite" >
</div>
<sl-render ng-reflect-image-url="xxx">
<div tabindex="0">
<button tabindex="0">Open</button>
</div>
<div aria-atomic="true" aria-live="polite" >
</div>
</sl-render>
As you can see, there are multiple sr-only
element in the example, but I only want the sr-only
that's inside sl-render
tag. Here's a not-so-clean solution:
- query
document.getElementsByTagName('sl-render')
- based on 1, query another
document.getElementsByClassName('.sr-only')
sincesr-only
is insidesl-render
tag
I am looking for a cleaner solution than the above, perhaps a built-in function to find sr-only
class that is below imageBackground
class?
CodePudding user response:
- Use
querySelector
orquerySelectorAll
with the selectorsl-render > div.sr-only
.sl-render > div.sr-only
will select all<div >
which is an immediate child of any<sl-render>
elements.
- TypeScript doesn't (yet) support type-safe results of
querySelector
but this is one of situations where usingas
is fine:querySelector
's return-type should be refined toHTMLElement | null
or a subtype there-of (e.g.HTMLDivElement | null
.querySelectorAll
's return-type should be refined toNodeListOf<HTMLElement>
(there is no need for the type-union with| null
as it's a collection-type).
Like so:
const srOnlyDivsInSLRenderElements = document.querySelectorAll( 'sl-render > div.sr-only' ) as NodeListOf<HTMLDivElement>;
for( const div of srOnlyDivsInSLRenderElements ) {
console.log( div.outerHTML );
}