Abderrahmane TAHRI JOUTI
Abderrahmane TAHRI JOUTI

Reputation: 4273

Is it OK to access <style> and <script> elements in this way?

Is this good CSS practice?

<style id="magic"> - so that I could, if I wanted - add CSS propreties using JavaScript (meaning: editing the <style> element from JavaScript) to affect elements in the document without me making the script go through each of the matched elements.

<script style="display: block; white-space: pre;"> So that I could share scripts inside a blog post along with a demo, without me being forced to write a version for the blog post and an other one for the demo.

(This is just hypothetical)

Upvotes: 2

Views: 193

Answers (1)

thomasrutter
thomasrutter

Reputation: 117411

In your first case (modifying style definitions in the <style> element using Javascript), you may find a couple of road bumps:

  1. Different browsers cope with this differently. In IE (at least, older versions), you will have to modify the .styleSheet.cssText property of the style element, and in other browsers you just need to add text nodes as children to it (note, it's possible that .innerHTML works universally; I just never used that).
  2. Appending new style rules is easier than replacing existing ones, especially when you are treating the rules as just text.
  3. Browsers (may) have a limit to the number of style rules per page. Though this will be in the thousands, you could hit limits if you set up style rules in a loop (without somehow purging old ones).

Other than that, go for it. It's probably a good alternative to setting inline styles.


In your second case, I'm sorry but that's just not possible (or if it is, it's definitely not recommended). You cannot display the textual contents of a <script> element as text using CSS, as well as executing it as Javascript. For a start, HTML parsers switch into a different mode while they're parsing the contents of a <script> element.

The preferred method for showing your Javascript source code alongside a demo is to have a separate, display-friendly version of the code for display (in a <pre> element, for example).

Upvotes: 3

Related Questions