How To Use HTML5 Data-* Attributes with JQuery and Selenium
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:
[attributeName="attribute value"].
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.
References: jQuery attribute selectors Selenium Web Driver – Locating UI Elements