0

This is a kind of a follow-up for this thread, someone commented that I shouldn't post it there: Instead of manipulating all elements of a given class, it is possible to alter the class itself.

I do not want to use a function, but rather manipulate a style attribute directly. I do not trust the position of the relevant stylesheet within the other stylesheets, so I added an id to the stylesheet: <style id="items_style">. I haven't found documentation, so by trial and error I found a combination that works at both Chrome and Firefox. Any thoughts?

document.getElementById("items_style").sheet.cssRules.item("ul-tags").style.visibility = 'hidden'
TylerH
  • 20,799
  • 66
  • 75
  • 101
Ilan
  • 23
  • 5
  • 1
    It's possible, but weird and fragile. I'd insert a new stylesheet of your own instead. Since you're coming from a JS context, manipulating the styles of elements directly with JS would make even more sense in most situations. – CertainPerformance Jan 15 '22 at 17:02
  • It is "my" stylesheet. I want to use this method to show and hide all elements of given class. Someone claimed that this method is more efficient than looping through all elements. I ask because I really don't know how browsers interpret javascript, why do you mean it is fragile? – Ilan Jan 15 '22 at 17:13
  • I don't know about the relative efficiency, but I've never once heard of a situation where it's enough of an issue to warrant a change like this. `.item` is a bad idea because it [depends on the rule index](https://developer.mozilla.org/en-US/docs/Web/API/CSSRuleList/item) (it doesn't accept a string) and the rule index could easily change if you make any change to the stylesheet; it's fragile. – CertainPerformance Jan 15 '22 at 17:17
  • `.item("ul-tags")` does work for me on Chrome and Firefox, do you mean that it is not officially supported? – Ilan Jan 15 '22 at 21:08
  • Is the rule that you're trying to change the first in the stylesheet? It could be that the string just isn't parsed, and it accesses the first rule by default. MDN, at least, says that the only parameter allowed is a number. – CertainPerformance Jan 15 '22 at 21:11
  • You are right: I changed the string, and the same class was affected. So no simple way for altering the class? – Ilan Jan 16 '22 at 06:50
  • Iterating over the elements with JS *is* simple IMO. You can insert a whole new stylesheet too, I'd consider that simple, just pretty weird. – CertainPerformance Jan 16 '22 at 06:51
  • What's your question? It's unclear what you are asking. – TylerH Jan 17 '22 at 15:22

0 Answers0