I’m trying to add an inline style to elements in a page that have a specific computed style attribute.
For instance:
<head>
<style>
p.mim {
cursor:pointer;
}
a.fif {
cursor:pointer;
}
</style>
</head>
<body>
<p class="mim">prova</p>
<a class="fif">prova</a>
</body>
I want to add an inline style “cursor:wait” to each element that has “cursor:pointer” set in the computed style:
<body>
<p class="mim" style="cursor:wait;">prova</p>
<a class="fif" style="cursor:wait;">prova</a>
</body>
This is what I tried:
var elms = document.getElementsByTagName("*");
for (var j = 0; j < elms.length; j++) {
var crs = getComputedStyle(elm, null).getPropertyCSSValue('cursor') || "";
crs = crs.replace(/\s/g, "").toLowerCase();
switch (crs) {
case "pointer":
case "Pointer":
case "POINTER":
elm.style.cursor = "wait";
break;
}
});
Your code is redundant for several reasons, and incomplete for others.
Firstly,
getComptedStyledoesn’t exist in earlier versions of IE. They instead use thecurrentStyleproperty. Thankfully it is absurdly easy to shim this:Now that that’s been solved, remove that
nullargument as it is completely redundant. Actually, I didn’t even knowgetComputedStylehad a second argument, but that’s just me.Next, you can get the cursor property just by getting
.cursor(or['cursor']) instead of that.getPropertyCSSValuecall (which again I have never heard of…). You can also drop the|| ""sincegetComputedStylewill return an empty string if thecursorproperty has not been set.You don’t need to trim spaces, but switching to lowercase seems like a good idea just to be on the safe side.
… But then, immediately after
toLowerCase(), you check THREE different capitalisations of the word? Really?Additionally, you never define
elm(which is where your actual problem is), and you should cache the value ofelms.length.The final code should look like:
If you want to be able to undo this, you will need to store an array of elements that you’re modifying, loop through it and remove the style (
.style.cursor = "";).