简体   繁体   中英

Modify css class with Javascript doesn't work

I'm currently writing a little chrome extension to modify an existing site. I try to modify one div element if the child contains an attribute with the value (for example red, blue, ...). If the child contains a value with the attribute value red I want the parent div colored in red and so on.

I've worte this JS:

//find the parent div element
element = element.getElementsByClassName("existing-class-to-find-div")[0];
// check if the attribute from the child is blue
...
if (color == blue){
   element.className += " RedColorClass";
}

if I printout the elmenent with element.outerHTML or the className everything is fine and I see the new value. BUT on the actual site there is still the old value and it isn't changed. Do I have to trigger something to refresh the html site or so?

使用element.classList.add("RedColorClass")或者,如果使用jQuery:

 $(element).addClass("RedColorClass");

If doing this without a lib, the style sheet object might be a better target to modify.

The this I am assuming is changing the background to red for the class .existing-class-to-find-div, based on comments. It is best to move that info into the question.

The style sheet itself is a different object.

var CSSStyleSheet = document.styleSheets[0]; /*danger this is first style sheet not necessarily the correct sheet */
CSSStyleSheet.addRule(".existing-class-to-find-div", "background-color:red");

The source code of the style sheet will not be changed, but the devtools should show the change.

On the code which is pasted vars color and blue are not defined. I suspect that is where the problem is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM