Is there a way for me to retrieve the locator value of a webelement?

How can I retrieve the selector value used in a selenium webelement in javascript?

Let's say I have the following object:

var el = browser.driver.findElement(by.id('testEl'));

I want to extract the text 'testEl' from this object and utilize it elsewhere, regardless of the selector type (by id, by css, etc.).

In Protractor, I could achieve this using: console.log(el.locator().value); This would output the text 'testEl'.

However, when dealing with just plain selenium selectors without Protractor, I am informed that .value() is not a valid function.

Is there any method to retrieve this locator/selector value?

EDIT:

The objective: Obtain the locator text from a selenium webElement

The use case: For functions such as getVisibleElement

The scenario: Working on a page where there may be an unknown number of elements with a specific selector, some hidden and others visible. There is no explicit hidden tag in this section of the element to target. The aim is to only retrieve the visible elements.

In Protractor:

function getVisibleElementByPageObject(protractorWebElement){
    var allElementsOfSelector = element.all(by.css(protractorWebElement.locator().value));
    var displayedElement = allElementsOfSelector.filter(function(elem) {
        return elem.isDisplayed('cannot find' + ' ' + protractorWebElement.locator().value);
    }).first();
    return displayedElement;
}

var exampleEl = $('[name="test"]');
var visibleExampleEl = getVisibleElementByPageObject(exampleEl);

I wish to access the locator so that if I were to adjust the selector in the future, I would only need to modify it in one location - the page object where the element is defined.

I could store the string in a variable and pass it whenever declaring an element or utilizing similar functions, but it would require creating a new standard for setting up page objects. It would be convenient to access the locator in selenium similarly to how it's done in Protractor above.

Answer №1

There is no need to fetch the locator from the webElement, as you should already have it when you first use it to locate the element. If your page objects are not set up in this way, then you are approaching it incorrectly.

An example in webdriver.js illustrates this concept:

* var link = element.findElement(firstVisibleLink);
*
* function firstVisibleLink(element) {
* var links = element.findElements(By.tagName('a'));
* return webdriver.promise.filter(links, function(link) {
* return links.isDisplayed();
* }).then(function(visibleLinks) {
* return visibleLinks[0];
* });
* }

Therefore, you can define functions like:

var firstElement = function(locator) {
return browser.driver.findElement(locator);
};
var firstVisible = function(locator) {
var elements = browser.driver.findElements(locator);
return browser.driver.promise.filter(elements, function(el) {
return el.isDisplayed();
}).then(function(visibleElements) {
return visibleElements[0];
});
};

var testLocator = by.css('[name="test"]');
var E1 = firstElement(testLocator);
var E1v = firstVisible(testLocator);

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

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it. Using ...

Tips for positioning a modal in the center specifically for zoomed-in mobile devices

I created a modal that uses the following function to center itself: center: function() { var top=Math.max($window.height() - $modal.outerHeight(),0) / 2; var left=Math.max($window.width() - $modal.outerWidth(),0) / 2; $modal.css({ ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

Avoiding GulpJs freezing with effective error handling techniques

I am currently in the process of converting my sass files to css and encountering some issues. Specifically, I am struggling with handling errors during the sass conversion process. Whenever there is an error, it causes gulp to hang, requiring me to rest ...

Convert the JSON data received from a jQuery AJAX call into a visually appealing HTML table

Utilizing AJAX as the action, I have created a search form. In the success of the AJAX request, I am seeking a way to update a specific div without refreshing the entire page. Below is my form: <?php $properties = array('id' => &ap ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

"Sending a file (Image) through NextJS API Routes to an external API: A step-by-step guide

I am currently using a combination of NextJS (SSR and SPA for authorized dashboard) with Django Rest FW on the backend. To handle authentication, I employ JWT tokens stored in cookies. As a result, it is necessary to have a middleware at /pages/api/* that ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

The CSS Bootstrap 4 class 'input-group-append' is not functioning properly. Just recently, the styles were displaying correctly

My web application using AngularJS 1.7.8, jQuery 3.3.1, Bootstrap 4.3.1, and various other CSS and JS libraries worked seamlessly last week. However, today I noticed an issue with the button visualization. To Replicate: Visit openskymap.org to see my d ...

Initializing Three.js to load the model

I have a 3D model that I initially had in the 3DS format. I then converted it to OBJ and finally to JS format. Now, my goal is to load this model into another JS file. Below you'll find the code snippet I've written for this purpose: var loader ...

Evaluating h1 content in HTML using Angular Protactor testing

I am completely new to end-to-end testing. I have a login page in my application that should be displayed to users when they log out. However, I am facing an issue with retrieving the text from a specific div element containing an h1 tag, leading to unexpe ...

Tips for ensuring that a server waits until a database connection is successfully established using node.js, MongoDB, and Express

I have a server.js file and a database.js file In the server.js file, I have the following code: const express = require('express'); var db = require('./database'); const app = express(); . . some get/post methods app.listen(3000); . ...

Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema: { guildId: { type: String, required: true, unique: true }, systems:{ reactChat:{ type: Array, required: true, ...

Issue with managing timezones in Angular with CDT/CST offsets

I have a date in UTC format that I need to convert to CST. It is 5 hours ahead of UTC during CDT and 6 hours ahead during CTC. The UTC date is '2016-09-07T05:00:00Z' <body> <div ng-app="myApp" ng-controller="datCtrl"> <p>Da ...

Contrasting BeforeClass and BeforeTest in TestNG

According to the TestNG official documentation: @BeforeClass: This method will be executed before the first test method in the current class is called. @BeforeTest: This method will be executed before any test method that belongs to the classes inside th ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...

Clicking a button with Java Selenium

While trying to navigate all the pages on a website, I encountered an issue where after scrolling to the second page, I received an exception stating that the element does not exist on the page. Upon further investigation, I realized that the CSS selecto ...

Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer. Recently, I stumbled upon a fascinating C++ library for creating a web se ...

Deciphering Encrypted JSON Data

In need of help with our app that generates complex JSON objects where properties and values are in hexadecimal format. How can we convert them back to strings? Example Object: { "636f756e747279": { "6e616d65": "43616e616461", "6 ...