1

How can I get css property for selector?

having html

<body>
  <a class="my_class" href="/" title="link"/>
</body>

and some properties for my_class

.my_class {
  color: red
}

in JS code I'm using cheerio lib:

var content = cheerio.load(html_content_page);
var selector = "a.my_class";

So, how can I get color property using above selector?

Bob
  • 773
  • 1
  • 10
  • 20
  • Ok, answer on similar question from maintainers: https://github.com/cheeriojs/cheerio/issues/357#issuecomment-31659300 – Bob Apr 08 '17 at 16:21

2 Answers2

1

Try this:

$('.my_class').css('color')
Pang
  • 9,564
  • 146
  • 81
  • 122
  • Possible duplicate of http://stackoverflow.com/questions/20377835/how-to-get-css-class-property-in-javascript – Sloan Thrasher Apr 08 '17 at 16:05
  • Guys, thank for fast reply, it doesn't work for me because I'm using 'cheerio' lib rather than 'jquery', so it seems to me that this lib can only parse css properties enclosed in 'style' tag within html, but in my case they are in separated css file. – Bob Apr 08 '17 at 16:10
0

Javascript, you can use getComputedStyle() for inline styling or rules declared in stylesheet

Snippet below

var a=document.getElementsByTagName('a')[0]
console.log(getComputedStyle(a).color);
console.log(getComputedStyle(a).backgroundColor);
.my_class {
  color: red
}
<body>
  <a class="my_class" href="/" title="link"/ style="background:blue">
</body>
repzero
  • 8,254
  • 2
  • 18
  • 40
  • I think that I couldn't pass Cheerio object into getComputedStyle function?! – Bob Apr 08 '17 at 16:20
  • I'm using cheerio lib for parsing html page (from arbitrary site), so this page keeps css rules in separated file I've found desired answer there: https://github.com/cheeriojs/cheerio/issues/357#issuecomment-31659300 – Bob Apr 08 '17 at 16:26