// nobulb

// nobulb

CSS selectors with multiple HTML attributes

Software Engineering

Something I had been banging my head about recently… CSS selectors on multiple attributes. No doubt, CSS selectors are powerful. Selecting on ids and classes are a cinch. And in case you didn’t know, you can string multiple classes together in a selection.

div#id.class1.class2.class3

Note: You could probably string multiple ids in a selector, but most proper engines will barf at you or simply return nothing. Despite the utility in being able to select multiple elements by their respective ids in one selector, this is poor form. If you find yourself doing this often, you might want to give regularly selected groups of elements a common class.

But even more impressively, you can do this on other HTML attributes. (Especially useful in Selenium when trying to verify specific types of input fields.) I was trying to verify a specific UI interaction where a password field would be revealed as plain text when in focus and returns to an obfuscated password field on blur. Unfortunately, I couldn’t figure out how to verify that a SPECIFIC field needed to have both name=‘myformfield’ AND type=‘password’. A single attribute can be selected as the following:

div#id.class1[name='myformfield']

Then it occurred to me that I might be able to string together multiple attribute selections similar to multiple class selections. Wouldn’t you know, it worked?! At least, it works in version 1.4.3 of jQuery’s Sizzle (its CSS selection engine) and 1.2.0 of Selenium IDE.

div#id.class1[name='myformfield'][type='password']

Awesome. Hope this helps someone.