How can I use :hover to change element properties which were created with javascript?

Viewed 71

I have an element which have created with javascript (in this case it is a div element). Javascript is also used to style the element's background color. When I do this, css :hover for the element to change the background color doesn't work.

script.js

box = document.createElement("div");
box.className = "box";
box.style.backgroundColor = "red";
document.body.appendChild(box);

style.css

.box {
    width:100px;
    height:100px;
}

.box:hover {
    background-color: green;  /*doesn't work*/
}

After testing, I found that applying the background color using js cancels out both css for the background color and css for the background color in :hover. Other properties defined in :hover do work, but only if not already defined during the creation of the element with js.

I am looking for a solution that would able to create a div element of any color with js and on hover change the color to green (it doesn't necessarily have to be with css).

2 Answers

!important overrides other styles:

box = document.createElement("div");
box.className = "box";
box.style.backgroundColor = "red";
document.body.appendChild(box);
.box {
    width:100px;
    height:100px;
}

.box:hover {
    background-color: green !important;  
}

this way:

your code doesn't because html element style attribut have priority on css

box = document.createElement("div");
box.className = "box";
 
document.body.appendChild(box);

 
.box {
  width            : 100px;
  height           : 100px;
  background-color : red;
  }

.box:hover {
  background-color : green;   
  }

Related