Wednesday, March 27, 2013

Replace XPath with Css selector






If you know css selectors, those are much more easier (and will work fine with IE without any problem ) than xpath even though they can't replace entire xpath.


Consider below HTML tags


 <div id="firstDiv">This div tag has static id </div>

 <p id="paragraps_dynamic_1234">This p tag has dynamic id</p>

 <a onclick="doThat()" title="doThatOperation">This a tag has multiple attributes</a>

 <h1 name="heading1" value="headName">This is heading</h1>


<div>
<input type="text" id="username" name="username"
<input type="password" id="password" name="pwd"
</div>

<h2 id="propertyUserData">This tag is for starts-with example</h2>


Tag XPATH CSS SELECTOR
div "//div[@id='firstDiv']" "div[id='firstDiv']"
p "//p[contains(@id,'paragraps_dynamic_')]" "p[id*='paragraps_dynamic_']"
a "//a[contains(@onclick,'doThat') and @tile='doThatOperation']" "a[onclick*='doThat'][tile='doThatOperation']"
h1 "//h1[@name='heading1' and @value='headName']" "h1[name='heading1'][value='headName']"
input "//div/input[@id='username']" "div > input[id='username']"
input "//h2[starts-with(@id,'propertyUser')]" "h2[id^='propertyUser']"

By seeing above locators we can conclude some points regarding css selectors

  • Using css selector we can access particular node or immediate child of any node
  • Can combine as many conditions as we want for single node.
  • Can achieve starts-with, contains functionality using ^,* symbols respectively. 
  • We can't traverse back using css selector.
  • We can't go to  the siblings also (preceding as well as following)



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.