Should I use ids to locate elements?

2.2k views Asked by At

Started with Angular and Protractor.

It just feels wrong to write some heavy css selectors which will break instant when you change something. Using ID's would make testing way easier.

I'm not using any id attribute for styling yet. Are there any drawbacks using ids for testing I haven't considered?

1

There are 1 answers

0
alecxe On BEST ANSWER

The general rule is to use IDs whenever possible assuming they are unique across the DOM and not dynamically generated. Quoting Jim Holmes:

Whenever possible, use ID attributes. If the page is valid HTML, then IDs are unique on the page. They're extraordinarily fast for resolution in every browser, and the UI can change dramatically but your script will still locate the element.

Sometimes IDs aren't the right choice. Dynamically generated IDs are almost always the wrong choice when you're working with something like a grid control. You rely on an id that is likely tied to the specific row position and then you're screwed if your row changes.

Also, in general try to use the "data-oriented" approach: by.model, by.binding, by.repeater locators, or if you rely on class names, choose them wisely: do not use layout-oriented classes like .col-xs-4 or .container-fluid.

See also these related topics: