Sidius
Sidius

Reputation: 414

Read and print the CSS values of a class with pure Javascript

I am trying to create a function, which:

Here's where I am so far:

HTML:

    <span class="slap0" data-finddeclaration="element">The great white fox</span>
    <div class="description" data-writedeclaration="element">

    </div>

    <span class="slap1" data-finddeclaration="element">The great white fox</span>
    <div class="description" data-writedeclaration="element">

    </div>

    <span class="slap2" data-finddeclaration="element">The great white fox</span>
    <div class="description" data-writedeclaration="element">

    </div>

    <span class="slap3" data-finddeclaration="element">The great white fox</span>
    <div class="description" data-writedeclaration="element">

    </div>

JS:

function readOutCssRules() {
var dataElement = document.querySelectorAll('[data-finddeclaration="element"]');
var classRules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
var writeDataElement = document.querySelectorAll('[data-writedeclaration="element"]');

for (var i = 0; i < dataElement.length; i++) {
    dataElement[i].className;
    if (classRules[i].selectorText == "." + dataElement[i].className) {
        console.log(classRules[i].cssText);

        writeDataElement[i].innerHTML = classRules[i].cssText;
    }
}


}
readOutCssRules();

But the function is not working as expected. Any ideas? Thanks in advance.

Upvotes: 1

Views: 989

Answers (2)

HudsonPH
HudsonPH

Reputation: 1868

Check this

https://jsfiddle.net/g6tu77mg/1/

var element = classRules[i].cssText
var css= element.substring(element.lastIndexOf("{")+1,element.lastIndexOf("}"));
writeDataElement[i].innerHTML = css;

Output:

The great white fox
color: blue;
The great white fox
color: red;
The great white fox
color: yellow;

Upvotes: 1

Ygalbel
Ygalbel

Reputation: 5519

Your code is working.

You just have to remove one line in the for loop:

for (var i = 0; i < dataElement.length; i++) {
    //dataElement[i].className;   --> remove this
    if (classRules[i].selectorText == "." + dataElement[i].className) {
        console.log(classRules[i].cssText);

        writeDataElement[i].innerHTML = classRules[i].cssText;
    }
}

After that changes it will work, as you can see in this fiddle.

Upvotes: 1

Related Questions