Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

  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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • Use querySelector or querySelectorAll with the selector sl-render > div.sr-only.
    • sl-render > div.sr-only will 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 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 );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading