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?
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.
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.
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.
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/
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 ')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With