Reputation: 5735
Get the rendered style of an element (Should be able to handle inline CSS also)
I have been learning Nokogiri and understand how to select a node based on an ID or Class. However, I would like to select a node/element and get back the specific CSS styles assigned to it, including inherited styles.
CSS Style Sheet:
<head>
<style type="text/css">
.myfont {font-family: Times New Roman: font-size: 80% }
.bold {font-weight: bold}
.50_font_size { font-size:50% }
</style>
</head>
HTML:
<Body>
<div id="article1" class="myfont">
<div id="title1" class="bold">
My Title Text
<div id="author1" class="50_font_size">
By First Name Last Name
</div>
</div>
General article text. General article text. General article text.
</div>
</div>
In the above example, I would like to use...
require "nokogiri"
document=Nokogiri.HTML(HTML_String)
#Hoping for something like the following:
author_css = node.css_style("author1")
puts author_css
#=> {font-family=>"Times New Roman",
#=> font-weight=> "bold",
#=> font-size=> 50%}
As you can see it should output the inherited items, so that I get the correct CSS of the element. What is the best way to get this result?
Upvotes: 2
Views: 874
Reputation: 160551
You can't do it with Nokogiri by itself. Using CSS_Parser will supply the missing piece:
require 'nokogiri'
require 'css_parser'
include CssParser
html = <<END_HTML
<head>
<style type="text/css">
.myfont {font-family: Times New Roman: font-size: 80% }
.bold {font-weight: bold}
.50_font_size { font-size:50% }
</style>
</head>
<body>
<div id="article1" class="myfont">
<div id="title1" class="bold">
My Title Text
<div id="author1" class="50_font_size">
By First Name Last Name
</div>
</div>
General article text. General article text. General article text.
</div>
</div>
</body>
END_HTML
doc = Nokogiri::HTML(html)
css = doc.at('style').text
parser = CssParser::Parser.new
parser.add_block!(css)
author_div = doc.at('div#author1')
puts parser.find_by_selector('.' + author_div['class'])
Which outputs:
font-size: 50%;
To get the inherited CSS you'll need to start at the top of the document and drill down to your desired node, figuring out what parent node's settings will affect your target node.
Upvotes: 5