slwr
slwr

Reputation: 1175

Javascript: add an inline style to elements in a page that have a specific computed style attribute

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;
    }
});

Upvotes: 2

Views: 1486

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Your code is redundant for several reasons, and incomplete for others.

Firstly, getComptedStyle doesn't exist in earlier versions of IE. They instead use the currentStyle property. Thankfully it is absurdly easy to shim this:

if( typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;};

Now that that's been solved, remove that null argument as it is completely redundant. Actually, I didn't even know getComputedStyle had a second argument, but that's just me.

Next, you can get the cursor property just by getting .cursor (or ['cursor']) instead of that .getPropertyCSSValue call (which again I have never heard of...). You can also drop the || "" since getComputedStyle will return an empty string if the cursor property 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 of elms.length.

The final code should look like:

if( typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;};
var elms = document.getElementsByTagName("*"), l = elms.length, i;
for( i=0; i<l; i++) {
    if( getComputedStyle(elms[i]).cursor.toLowerCase() === "pointer") {
        elms[i].style.cursor = "wait";
    }
}

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 = "";).

Upvotes: 1

Related Questions