Initially, I have a string of html and text content.
I want to add css stylings to certain html elements from the above string. How can I achieve this using hpricot gem?
I am able to scrap out the html elements by using each loop. But how do I take it further?
For eg, I have the following string:
"<pre>//code snippet 1</pre><p>Table:</p><table><tbody><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></tbody></table>"
Then, I can access all the td elements by using:
string.search("//td").each do |ele|
//some code needed to add css to ele
end
Hpricot has been abandoned, so you'd be better off using for example Nokogiri.
I made this example using Nokogiri. You can use the
[]=method to add arbitrary attributes to a node. We use this to add astyleattribute.I used DocumentFragment, because otherwise Nokogiri will make sure that our fragment becomes a full HTML document by adding the
htmltag.Keep in mind that adding inline CSS styles like this is considered bad practice.