XNRL
XNRL

Reputation: 63

Javascript: get content of an element with incorrect style definition

I'm creating a stylesheet for a certain site, using javascript to assign classes to certain elements. For whatever reason some of 'td' elements use weird class assignments and inline styles, so I loop over them, clean them up and assign proper class names to reference in external stylesheet.

I don't have access to the site itself (nor administrative permission to change anything) so I use Stylish and Greasemonkey for Firefox (plus Adblock to dispose of the original stylesheet).

Here is a little part of js code responsible for that:

var cellStyleBg = cCell.style.backgroundColor;
if (cellStyleBg) {
switch(cellStyleBg) {
    case 'white':
        cCell.removeAttribute('style');
         if ( cCell.parentNode.nodeName == 'TR' ) {
             cCell.parentNode.className = 'deadlineSet';
         }
         break;
...

The problem is there is one particular case where this doesn't work:

<td class="td2h" style="background: dd97f0;">

As you can see, there is no octotorp in front of the color code. I assume that is the reason in this one case the variable cellStyleBg is 'null'.

I tried (instead of 'cCell.style.backgroundColor') to use 'cCell.style' and 'cCell.style.background', but they don't return plain text for me to parse.

What can I do to handle this particular case?

Upvotes: 3

Views: 61

Answers (1)

LostInComputer
LostInComputer

Reputation: 15420

I think the only way to go is to get the raw value of the style attribute. You do this by

//will output background: dd97f0
cCell.getAttribute('style');

If needed, you can breakdown the style into key value pairs using this snippet

//give "background: dd97f0", will output "background=dd97f0"
var stylePattern = /(.*?):([^;]*);?/g
while (match = stylePattern.exec(style)) {
    console.log(match[1].trim() + "=" + match[2].trim());
}

Upvotes: 1

Related Questions