I recently wrote a post about when it’s appropriate to use CSS classes. In it, I made the case that HTML5 data-* attributes can be used instead of CSS classes to identify elements on a page. In this post, I’ll describe exactly how to do this.
Find Me a City
Let’s start with the following HTML fragment:
<div data-element="city">Los Angeles</div>
Here we have a
div which displays the name of a city and has a
data-element attribute to identify it as such.
To find this element, we’ll need to use a CSS Attribute Selector. The syntax for attribute selectors is pretty straight-forward:
For instance, to find this element in jQuery, we’d do this:
var city = $('[data-element="city"]');
The same CSS attribute selector can be used in Selenium:
WebDriver driver = new FirefoxDriver() driver.get("http://www.oursite.com") WebElement element = driver.findElement(By.cssSelector('[data-element="city"]'))
As you can see, CSS attribute selectors make using data-* attributes a painless affair. This simplicity, combined with the fact that you can get semantically rich markup without overloading the
class attribute, make data-* attributes worth considering.
jQuery attribute selectors
Selenium Web Driver – Locating UI Elements
You may also like:
Did you love / hate / were unmoved by this post?
Then show your support / disgust / indifference by following me on Twitter!