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

Reactive property cannot be defined on an undefined, null, or primitive value within the context of Bootstrap Vue modal

Can someone please assist me with this error message? It says "app.js:108639 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value." I encountered this error while working with a Bootstrap Vue modal. Here is a snippet of my code: ...

What is the best way to remove an active item from a Vue v-list?

When using Vuetify's v-list-item directive, I encountered an issue where the active prop cannot be removed once an item has been selected. Here is my approach so far: <v-list-item-group pb-6 color="primary" class="pb-3 text-left"> ...

How can Selenium in Python be used to click a JavaScript button?

I need help automating the click of a button on a webpage using selenium Here is the HTML for the button: <div class="wdpv_vote_up "> <input value="7787" type="hidden"> <input class="wdpv_blog_id" value="1" type="hidden"> </div& ...

The terminal in VS CODE is not able to detect Stripe

When I attempt to run the command 'stripe listen' in the VS Code terminal, an error is thrown: The term 'stripe' is not recognized as the name of a cmdlet, function, script file, or operable program. Please check the spelling of the ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

Utilizing Python Selenium WebDriver to launch an Electron-based Application

Trying to skip using Spectron for End2End testing an electron app by leveraging my experience with Selenium Webdriver on Python. After reviewing the Chromedriver get started page and various resources that hint it's possible, I came up with this solut ...

A link is not allowed to be a child of another link

An issue arises in a React.js application Warning: validateDOMNesting(...): <a> cannot be nested under another <a>. Refer to Element > a > ... > a for more information. What is the significance of this warning? How can it be avoided ...

I'm having trouble persisting my mongoose model data in my MongoDB database

Hey there, I'm new to this and currently attempting to save the Amadeus object I've created into mongosh using the .save() method. However, after connecting to my file through node, editing the Amadeus object, and running amadeus.save(), I check ...

Guide to making two text boxes with SimpleDialog in jQuery Mobile

I came across the link below, but unfortunately it's not working for me. jQuery Mobile SimpleDialog with two Inputs? Is there anyone who can assist me after reviewing the code snippet provided below? <script type="text/javascript> ...

The appropriate exception to raise in a Selenium Automation scenario when locating a web element

Currently, I'm in the process of developing a unique "Selenium Wrapper Library" that consists of a set of methods designed for automating tasks on specific web portals. These methods encompass debug logging and other functionalities, which are then in ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Python Selenium: Troubleshooting the get_elements method not retrieving li items within ul tags

I am facing an issue while trying to retrieve li items within a ul element using the following code: driver.get('https://migroskurumsal.com/magazalarimiz/') try: select = WebDriverWait(driver, 10).until( EC.presence_of_element_locate ...

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

Access a webpage using a Python web-scraping tool to log in

Currently, I am employing Selenium WebDriver within Python to carry out a web scraping endeavor. My aim is to log in by inputting the necessary login credentials and subsequently clicking on the submit button. Although successful in entering the Username ...

Angular and JavaScript Performing Slide-Up Animation

Currently, I am working on creating a menu using Angular and JavaScript. My goal is to have this menu toggle between showing and hiding when a button is clicked. If you would like to view the code that I have written so far, you can check out the demo her ...

Extracting data from websites using Python's Selenium module, focusing on dynamic links generated through Javascript

Currently, I am in the process of developing a webcrawler using Selenium and Python. However, I have encountered an issue that needs to be addressed. The crawler functions by identifying all links with ListlinkerHref = self.browser.find_elements_by_xpath( ...

Utilizing browser local storage in web development

Currently, I am in the midst of working on an e-commerce platform, a project that holds significant importance for me as it marks my debut into major projects. For the first time, I am delving into the realm of local storage to manage basket data such as q ...

Tokenizing with jQuery UI

I have been following a tutorial that utilizes jQuery UI to generate Facebook tokens, as shown in this link: However, I am facing an issue where I need to pass two values through JSON: the ID and the NAME. The server-side script is structured as follows: ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...