Jump-Locate Element via CSSSelector

The idea to come up with the best cssSelector for an element remains same as that for xpath:

  • Identify the closest ancestor element which is relatively stable, and use it as your anchor element
  • Then jump along brief descendants to the desired element. Use ‘ ’ (white space between adjacent elements) instead of ‘>’ in the selector to skip those unnecessary nodes on the way.
    CSS syntax for:

    Direct descendents:>
    example: >div>div>ul>li>span
    Any descendents: (White space between nodes)
    example: div ul>li>span

Use the same htlm code snippet for our example:

<body>
<div class=”genres-wrapper wrapper”>
<ul class=”genres”>
<li class=”genre”>
<div class=”genre-btn” >
<div class=”genre-img” ></div>
<button class=”btn-circle check”>
<i class=”icon-check genre-btn-check”></i>
</button>
<div class=”genre-title”>Classic Rock</div>
</div>
</li>
<li class=”genre”>
<div class=”genre-btn” >
<div class=”genre-img”></div>
<button class=”btn-circle check”>
<i class=”icon-check genre-btn-check”></i>
</button>
<div class=”genre-title”>Pop</div>
</div>
</li>
</ul>
</div>
</body>

Suppose that we want to locate ‘Pop’ element by css, where shall we start? Ul.genres.
And we want to skip div.genre-button, and end up with something like this:

ul.genres > li:nth-child(2) .genre-title

When we inspect an element in browser, it tends to give us complete css path to that element, so don’t rely on browser inspector completely. Instead, use it as a base and get rid of those unnecessary in-between nodes and only keep locating essence info by using jump-find ‘ ‘ instead of step-by-step sign ‘>’.

Useful tip: Different syntax to refer to descendants for CSS and XPath

Relationship CSS Xpath
Parent/child > /
Ancestor Blank ‘ ‘ //
Specific child :nth-child(index) [index]
Attribute value . for class # for ID
[attribute] [@attribute] [@attribute = value]

Leave a Reply

Your email address will not be published. Required fields are marked *