Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html elements with multiple css classes

I know how to get a list of DIVs of the same css class e.g

<div class="class1">1</div> <div class="class1">2</div> 

using xpath //div[@class='class1']

But how if a div have multiple classes, e.g

<div class="class1 class2">1</div> 

What will the xpath like then?

like image 599
seasong Avatar asked Oct 07 '10 11:10

seasong


People also ask

Can an HTML element have multiple CSS classes?

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them. If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations.

Can elements have multiple classes HTML?

Any HTML element can have as many different classes as needed to style the element using CSS effectively. To assign multiple classes to a single HTML element, you need to specify each class name inside the class attribute separated with a blank space.

How do you find an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.


2 Answers

The expression you're looking for is:

//div[contains(@class, 'class1') and contains(@class, 'class2')] 

I highly suggest XPath visualizer, which can help you debug xpath expressions easily. It can be found here:

http://xpathvisualizer.codeplex.com/

like image 147
Ioannis Karadimas Avatar answered Sep 21 '22 02:09

Ioannis Karadimas


According to this answer, which explains why it is important to make sure substrings of the class name that one is looking for are not included, the correct answer should be:

//div[contains(concat(' ', normalize-space(@class), ' '), ' class1 ')     and contains(concat(' ', normalize-space(@class), ' '), ' class2 ')] 
like image 20
Vic Seedoubleyew Avatar answered Sep 22 '22 02:09

Vic Seedoubleyew