Here’s the sample html:
<div aria-atomic="true" aria-live="polite" class="sr-only">
</div>
<sl-render ng-reflect-image-url="xxx">
<div class="imageBackground" tabindex="0">
<button class="OpenButton" tabindex="0">Open</button>
</div>
<div aria-atomic="true" aria-live="polite" class="sr-only">
</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-onlyis insidesl-rendertag
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?
>Solution :
- Use
querySelectororquerySelectorAllwith the selectorsl-render > div.sr-only.sl-render > div.sr-onlywill select all<div class="sr-only">which is an immediate child of any<sl-render>elements.
- TypeScript doesn’t (yet) support type-safe results of
querySelectorbut this is one of situations where usingasis fine:querySelector‘s return-type should be refined toHTMLElement | nullor 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| nullas 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 );
}