I want to change background color each time when my_div recive class ‘selected’.
So far I’ve got this:
$(document).ready(function() {
if ($('#my_div').hasClass('selected')) {
$("body").css({backgroundColor: '#111'});
}
});
but it don’t work.
What’s wrong?
There is a piece of code which is giving your element the
selectedclass. This piece of code effectively changes your element’sclassto beclass = "whatever classes previously existed insertednewclass".One way to do what you’re trying to do, is to find the function which is adding/removing the class, and hook into it, for example:
I assume your case is not as simple as this. However this is possible even if the function is in an external library, though it’s risky if the library changes its internal behavior.
If you cannot do that and MUST reactively detect a class attribute modification, you can use the deprecated DOM Level 2 mutation events http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents which are vaguely supported in non-IE browsers. You can see if it is supported via
$.bindin jQuery; if it isn’t supported in jQuery, you can useyour_element.addEventListener(...)which is the native way to do things (which is basically all that jQuery is using under the covers).