CSS vs XPATH vs ID



  • Selecting an element with unique ID say "sign", which is the preferred method:

    1. By.id("sign");
    2. By.xpath("//[@id="sign"]");
    3. By.css('[id="sign"]');

    Lets filter out xpath because By.id uses document.getElementById() under the hood and it can be faster. But when we compare with css and id what is the difference and how exactly does document.getElementById() works

    Does the choice of locator have any relationship with the web technology eg : angularjs



  • Here is the specification for how a webdriver conform implementation should handle element retrieval https://www.w3.org/TR/webdriver/#xpath. XPath is incredibly slow because every layer of your path is basically a loop over all children within the current scope.

    id and css selector leverage the fact that browsers are already really good at using those identifiers since they must be evaluated while rendering the page. How exactly they're implemented depends on the specific browser but the outlines are defined here https://www.w3.org/TR/selectors-api2/ (and I'd really encourage working through it since it helps understanding browsers and by extension web applications). The short version comes down to the fact that your browser, when it has rendered the page, has already a mapping for important subspaces in your page from which it can work off to find your specific selector with much less effort as it would need if you were to bruteforce your way through it using an xpath.

    Between id and css selectors ids tend to be a little bit faster since the lookup is basically the same for both but css selectors have to be parsed beforehand but in the end where talking differences of one digit milliseconds here.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2