Opting for CSS selectors over XPath locators for locating siblings in the DOM

Currently, the page object contains the following fields:

this.filterTeamDropdown = $("filter-item-edit .dropdown button");
this.teams = this.filterTeamDropdown.all(by.xpath("following-sibling::ul//li[contains(@class, 'dropdown-list-item')]"));

Considering the recommendation in the Style Guide against using XPaths, is there a way to replace the XPath locator for the teams field with a CSS selector?


In accordance with the suggestion not to use XPaths, are there any alternatives for having a CSS selector that navigates to the next sibling element starting from the current element? I understand that this may be complex, but I am open to exploring different options.

Answer №1

Absolutely refusing anything is unwise. My preference lies with CSS selectors as they are quicker than XPath for locating elements by id or CSS selector. However, the difference in speed is minimal, only a few milliseconds.

XPath does have some capabilities that other locators lack. For instance, it can find an element based on its contained text (excluding A tags). Nonetheless, I usually opt for CSS selectors when id fails to do the job.

I am not a fan of how many individuals rely solely on XPath for locating elements on websites like Stack Overflow. It sometimes seems excessive and inefficient. Many people simply right-click on an element in the inspector and copy the XPath without considering its fragility. This habit persists due to ease rather than knowledge.

Despite my reservations, I suggest referring to the W3C CSS Selector reference to help you in your search for suitable combinators. Without knowing your HTML structure, it's challenging to recommend specific combinator choices.

https://www.w3.org/TR/selectors/#selectors

https://www.w3.org/TR/selectors/#adjacent-sibling-combinators


After reading the comments on your question, I noticed that you were already aware of the + combinator. Have you considered using your initial CSS locator alongside the converted XPath string? While I cannot confirm its validity, I have combined the two locators from your code after converting XPath to a CSS selector.

filter-item-edit .dropdown button + ul li.dropdown-list-item

Answer №2

If you're working with Protractor, there's a unique approach to tackling this issue - utilize the locator() method of the parent element and combine it to create a selector for the child element:

this.dropdownButton = $("filter-item-edit .dropdown button");
this.filteredList = this.dropdownButton.$$(this.dropdownButton.locator().value + " + ul li.dropdown-list-item")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to expand ScrollToBottom to cover the entire screen height?

Check out this code sandbox that showcases a Logs React component functioning perfectly. The implementation incorporates react-scroll-to-bottom to display a page with a header and logs. What's interesting is that the log section dynamically adjusts i ...

Looking to efficiently output information generated within a headless browser in node.js

Is there a way to print out data created inside a Node.js running headless browser if console.log('Text') isn't working? For example: const pup = require('puppeteer'); const chrom = await pup.launch({headless:'new'}); ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

What is the method for adding a CSS class to the textContent in a HTML element?

Hi there, I'm currently trying to make some changes to the textContent of the HTML code below. However, it contains an <i> tag, so I'm wondering how I can change the textContent without affecting the <i> tag itself. Is there a way to ...

Enhancing a specific element in a view using Node.js alongside Express and EJS

My goal is to modify value2 on the server side and update the view accordingly. The question at hand is: How can I efficiently refresh the view with only the new value2? Server: var express = require("express"); var app = express(); app.set('view ...

Encountering a "Value cannot be null" error while using VS2015 Coded UI for Cross Browser testing with Chrome

While executing a Coded UI test against Chrome, the cross-browser console appears and the Chrome browser window pops up (without displaying the webpage), but then I encounter an exception: System.ArgumentNullException: Value cannot be null. Parameter n ...

Leveraging locators within Cucumber table elements

In my login Test, I conduct positive and negative scenarios using tables in cucumber. Scenario Outline: Login Given User navigates to Field And User enters a "<Username>" username And User enters a "<Password>" password When User clicks on th ...

Redirecting and styling following an HTTP post operation

Implementing Stripe on my Firebase-hosted website. Utilizing a Cloud Function to handle the transaction. I have integrated the Stripe Checkout within a button displayed directly on my single HTML page, which then directs to the /charge function in inde ...

"Can you tell me more about the purpose of $cacheFactory

I am struggling to find information on the purpose and functionality of $cacheFactory in application development. According to the Angular Documentation, "Factory that constructs cache objects and gives access to them." -- $cacheFactory However, this e ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Ways to minimize the occurrence of duplicate values in a table

In the application, I have a table where I add multiple values to an Array. These arrays display the values in the table columns, sometimes resulting in duplicate values. Below is a small example to illustrate the issue. What is the best way to eliminate ...

Confusion arises from conflicting Vue component script indentation guidelines

As I work on setting ESLint rules for my new Vue project, I am extending both eslint-plugin-vue and airbnb. All is well except for one issue - the indentation of the tag inside Vue components. The usual accepted format looks like this: <script> ex ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Error: 'POST Request Processing Failure: Content-Type Missing'

My front end Canvas is transformed into a png file that needs to be POSTed to a third party vendor's API. The response comes back to Node as a base64 file which I decode, but upon attempting the upload, an error occurs: Error processing POST reques ...

Updating the default download location with Firefox webdriver during execution

Is there a method to set a predefined download destination for Firefox during runtime without the folder selection window appearing? ...

Problem with a for loop: retrieve only the final item

Using the fileReader to read the content of selected files and appending it to the DOM creates a paragraph element for each file. However, when attempting to store each file's content in local storage, only the last item is being saved. What could be ...

The presence of double quotes in stringified JSON is undesired

I am currently working on a weather forecasting website where the API returns pure JSON data. However, when I convert this data to a string and add it to an element in order to display it on the webpage, I encounter a problem with double quotes appearing. ...

`Nextjs customizes the position of locales`

Currently implementing i18n translation in my project, the default root appears as follows: https://example.com/en/business/transaction Is it possible to customize the root to appear as: https://example.com/business/en/transacation Thank you. ...

Ways to delete an element from an array in MongoDB

I am a beginner in the MEAN stack development. I am currently working on implementing this and this. I have been using the $pull method, but it seems that it is not working for me. I suspect that the issue might be due to the differences in my MongoDB stru ...

When using AngularJS to poll a $resource at regular intervals, the promise that is returned from the $resource call does not automatically get resolved

Let's get to the important details: When I link a $scope variable in my controller directly to a $resource, Angular takes care of promise resolution automatically and updates my view as soon as data is received from the service. However, I need to per ...