Home > other >  Built In Method in Typescript to Find Class inside a Tag Name or a Sibling of a Class
Built In Method in Typescript to Find Class inside a Tag Name or a Sibling of a Class

Time:12-09

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:

  1. query document.getElementsByTagName('sl-render')
  2. based on 1, query another document.getElementsByClassName('.sr-only') since sr-only is inside sl-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 or querySelectorAll with the selector sl-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 using as is fine:
    • querySelector's return-type should be refined to HTMLElement | null or a subtype there-of (e.g. HTMLDivElement | null.
    • querySelectorAll's return-type should be refined to NodeListOf<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 );
}
  • Related