You could of course do the following (not recommended):
- Open the page you’re going to test in a browser
- Right-click the element on the page -> Inspect
- 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:
- 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. - Use the smallest selector chain that will give you the unique element.
- 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 classproduct-item
. Classes are not unique, but if we know where it sits in the DOM we can still get it this way. - 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 classproduct-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. - 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.
- Maybe your element is the first element on the page with the class product-item. You could use