Skip to content Skip to sidebar Skip to footer

How Can I Set A Css ":hover" On A DOM Created Element In JavaScript?

I'm using the DOM to manage a JSON response from an AJAX function I'm running. The script I'm writing needs to be completely portable, so I am defining the styles for the created e

Solution 1:

You can dynamically create and manipulate stylesheets. See here for some of the cross-browser issues with this approach.

I've got a wrapper function lying around which works around some of them; using it, the code would read

document.createStyleSheet().addRule('#myDiv:hover', 'background:#000000;');

Solution 2:

you may create element with predefined class:

.h:hover{color: #c00}

var elem = document.createElement('div');
elem.className = 'h'

Post a Comment for "How Can I Set A Css ":hover" On A DOM Created Element In JavaScript?"