Protractor: Efficiently Locating Sibling Elements

Protractor: Efficiently Locating Sibling Elements

11 April 2024 Stephan Petzl Leave a comment Tech-Help

When working with Protractor, a common task is to locate an element that is a sibling to another known element. This can be particularly challenging when you have a reference to one element, such as a link, but need to interact with its sibling, like an image. In this guide, we will walk through a practical solution to locate a sibling of a given element using Protractor.

Understanding the Problem

Consider the following HTML snippet where we have a link and an image within a div, and we want to locate the image based on the known link text ‘LINK’:

                
<div>
   <a href='...'>LINK</a>
   <img class='image' />
</div>
<div>
   ...
</div>
                
            

To begin, you might have located the link using Protractor’s browser.findElement method:

                
browser.findElement(by.linkText('LINK'))
                
            

Solution: Chaining Selectors with XPath

The solution involves chaining selectors and utilizing XPath to navigate from the known element to its sibling. Here’s the step-by-step approach:

  1. Use a CSS selector to locate the initial element (in this case, the link with the text ‘LINK’).
  2. Apply the by.xpath('..') locator to navigate to the parent of the initial element.
  3. Chain another CSS selector to locate the sibling element from the parent (the image with the class ‘image’ in this example).
  4. Invoke the desired action on the sibling element (such as clicking it).

Here is the Protractor code that accomplishes the task:

                
element(by.css('a[href="..."]')).element(by.xpath('..')).element(by.css('img.image')).click();
                
            

This code snippet demonstrates how you can select an element by its link text, navigate to its parent, and then select a sibling image element to perform an action.

Conclusion

Navigating the DOM to locate sibling elements can be a bit tricky, but with the right approach, it becomes manageable. The combination of CSS selectors and XPath provides a powerful way to traverse the DOM and find the elements you need to interact with in your Protractor tests. By chaining these selectors as shown, you can efficiently locate sibling elements and perform actions on them.

Like this article? there’s more where that came from!