Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use ids to locate elements?

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?

like image 494
boop Avatar asked Jun 16 '15 09:06

boop


People also ask

Is it better to use ID or class?

A simple way to look at it is that an id is unique to only one element. class is better to use as it will help you to execute what ever you want.

Why is id not recommended as a selector?

IDs shouldn't be used in selectors because these rules are too tightly coupled with the HTML and have no possibility of reuse. It's much preferred to use classes in selectors and then apply a class to an element in the page.

When should you use IDs in CSS?

The CSS id Selector The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Should you use IDs in HTML?

Only put required elements or attributes in HTML. You do not need to put ID attribute if it is not required, and you can always add ID attribute whenever required. Keeping only required elements in html will make it easy to read, clean, low on size and hence improves performance and speed.


1 Answers

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:

  • Best Practices for Watir and Selenium Locators
  • best way to detect an element on a web page for seleniumRC in java
like image 114
alecxe Avatar answered Sep 20 '22 00:09

alecxe