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.
CodePudding user response:
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.