Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nokogiri multiple css classes

How is it possible to select an html element that have two classes?

For example, how to select the element <p> bellow in an HTML document (given that it has two css classes) class='class1 class2'.

I tried to use the following:

  • doc.xpath("//p[@class~='class1 class2']")
  • doc.xpath("//p[@class~='class1']|[@class~='class2']")
  • doc.xpath("//p[@class~='class1',@class~='class2']")
  • doc.xpath("//p[contains(concat(' ', @class, ' '), ' class1 ') && contains(concat(' ',@class, ' '), ' class2 ')]")

but without success.

Thanks in advance

like image 719
massinissa Avatar asked Nov 19 '09 06:11

massinissa


1 Answers

Finally I found the RIGHT way to search multiple css classes with nokogiri (libxml) :

doc.xpath('//p[contains(@class, "class1") and contains(@class, "class2")]')

It's not perfect, because if <p> contains classes such as class10 and class20 the element will be selected, but for now it's enough for what I need. If you have more suggestions they are welcome!

Update

Here is a better solution to this problem using css only :

doc.css('p.class1.class2')

Thanks to Aaron Patterson :-)

like image 84
massinissa Avatar answered Nov 10 '22 17:11

massinissa