stack twitter tryhackme rss linkedin cross

Wilco van Esch

Skip to main content

Search results

    Working with WebdriverIO | Find the right selector to use

    You could of course do the following (not recommended):

    1. Open the page you’re going to test in a browser
    2. Right-click the element on the page -> Inspect
    3. Right-click the element in the HTML -> Copy -> Copy selector

    If you paste it, you get something like:

    #maincontent > div.columns > div > div:nth-child(15) > div > div > div:nth-child(6) > figure > a > img. pagebuilder-mobile-hidden

    Cool. Theoretically you could use this. It’s a unique reference to the element.

    It’s also horribly long and unwieldy.

    What you want is the shortest possible unique reference. The easiest way to get it is through using the element’s id tag. An id should always be unique. Example: $(#login). The # symbol is how you select by id. However, many elements will not have an id tag defined. In those cases you can:

    1. Use a custom data attribute defined by the developers. Example: $('[data-test="search"]'). This would require it to be added to the source code first. You can ask a developer or submit an MR yourself.
    2. Use the smallest selector chain that will give you the unique element.
      1. Maybe your element is the first element on the page with the class product-item. You could use $('.product-item'). This would select the first element in the DOM with the class product-item. Classes are not unique, but if we know where it sits in the DOM we can still get it this way.
      2. Maybe your element is the second element on the page with the class product-item. You could use $$('.product-item')[1]. Note the $$. We are selecting all elements with class product-item instead of the first one in the DOM. Then of those elements we’re selecting the second one. It’s a zero-indexed array, which means that 0 would select the first item and 1 would select the second.
      3. Maybe this is all Chinese to you. In that case here’s a simple trick for you. You could take the absurdly long selector you got from the DOM (#maincontent > div.columns > div > div:nth-child(15) > div > div > div:nth-child(6) > figure > a > img.pagebuilder-mobile-hidden) and simply remove all elements except the last one and put them back in one by one until they lead to a unique element.