in Web and Tech

Appending DOM Elements Dynamically

I couldn’t be sure whether it was fine to add pseudo-selectors for an element inline so I consulted Google. Most of the results said “no”, but one answer stood out because it dove deeper and proposed an interesting solutions – adding an element dynamically. Here’s the full reply:


Short answer: you can’t.

Long answer: you shouldn’t.

Give it a class name or an id and use stylesheets to apply the style.

:hover is a pseudo-selector and, for CSS, only has meaning within the style sheet. There isn’t any inline-style equivalent (as it isn’t defining the selection criteria).

Response to the OP’s comments:

See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically. Also see Change style sheet for some of the theory on the subject.

Also, don’t forget, you can add links to external stylesheets if that’s an option. For example,

<script type="text/javascript">
  var link = document.createElement("link");
  link.setAttribute("rel","stylesheet");
  link.setAttribute("href","http://wherever.com/yourstylesheet.css");
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(link);
</script>

Caution: the above assumes there is a head section.

Write a Comment

Comment