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

Does JavaScript 'Set' work for HTMLStyleElement objects?

In my website there are some duplicated <Style> elements in DOM. I am trying to use a Set in JavaScript to do some de-duplication for these elements. The code to generate non-dup elements is something like:

const CSSCache = new Set<HTMLStyleElement>();
const styles = document.getElementsByTagName('style');
for (let i = 0; i < styles.length; i++) {
   CSSCache.add(styles[i] as HTMLStyleElement);
}

I am wondering if the JavaScript Set able to unique-fy these HTMLStyleElement objects.

Also, some of these elelment doesn’t have any content, e.g. <style></style> but they have rules in element.sheet.cssRules inserted with insertRule (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule). I am wondering if Set works for these types of Style as well.

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 :

A Set contains values that are unique via the Object.is algorithm, which is nearly the same as how === works.

Separate <style> objects on the page, regardless of content are not ===, so you’ll get a Set with all <style>s on the page with your current code.

The same is true for any HTMLElement, and even true for plain objects.

const set = new Set();
const obj1 = {};
const obj2 = {};
set.add(obj1);
set.add(obj2);
console.log(set.size);

If you want to de-duplicate, you will have to go another route – such as iterating through the rules of each style.

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