Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source:

href="javascript:navigateToDiffTab('https://site_url/medications','Are you sure you want to leave this page without saving your changes?');" tabindex="-1">Medications

For privacy reasons, I've replaced the actual URL with "site_url."

I attempted to use the following code, but it didn't work as expected:

driver.findElement(By.cssSelector("a[href^='javascript:navigateToDiffTab'][href$='site_url/medications']")).click();

I prefer not to rely on id or linkText due to environmental and language differences.

If anyone could offer some assistance, it would be greatly appreciated.

Answer №1

Here is a code snippet that has worked well for me:

WebElement element= driver.findElement(By.cssSelector("a[href^='javascript:navigateToDiffTab'][href$='site_url/medications']"))

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);

If the provided code does not work for you, it could indicate an issue with your locator. In that case, try using a different locator or share some HTML code in your question so we can help you identify the correct locator.

I hope this helps! :)

Answer №2

The part of the selector that states href$='site_url/medications' suggests that the href should conclude with site_url/medications, but this is incorrect and the reason why you are not getting a match.

How about we simplify it to just "href contains 'medications'":

a[href*=medications]

Answer №3

alexce has pinpointed the issue with href$='site_url/medications' utilizing a suffix-match approach, however, it might be beneficial to outline and elucidate the array of CSS attribute selectors at your disposal.

[attr] Represents an element with an attribute name of attr.

[attr=value] Represents an element with an attribute name of attr and a value that exactly matches "value".

[attr~=value] Represents an element with an attribute name of attr where the value is a list of words separated by whitespace, one of which matches exactly as "value".

[attr|=value] Represents an element with an attribute name of attr. The value can either be exactly “value” or start with “value” followed immediately by “-” (U+002D). This selector is often used for language subcode matches.

[attr^=value] Represents an element with an attribute name of attr where the value is prefixed by "value".

[attr$=value] Represents an element with an attribute name of attr where the value is suffixed by "value".

[attr*=value] Represents an element with an attribute name of attr where the value contains at least one instance of the string "value" as a substring.

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

Guide on clicking hyperlinks within table columns on a webpage using Selenium web driver and saving the data

Below is the HTML code I am working with: Is there a way to select the link element in the tenth row? HTML image <table id="dataTableParticipantSearchResults" class="display" width="100%" cellspacing="0" cellpadding="0" border="0"> <the ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...

What guidelines should be followed for utilizing jQuery's Ajax convenience methods and effectively managing errors?

Imagine a scenario where I am trying to mimic Gmail's interface using jQuery Ajax to incorporate periodic auto-saving and sending functionalities. Error handling is crucial, especially in cases of network errors or other issues. Instead of just being ...

The Facebook bots are unable to crawl our AngularJS application because the JavaScript is not being properly

I have a unique setup where my website is built with AngularJS and Wordpress as a single page application. Depending on the routing of the page, I dynamically define meta tags in the controller. Here's a snippet of my HTML header: <meta property=" ...

The process of retrieving keys and values from localStorage in html5

I have stored some important key-value pairs in local storage. Now I need to retrieve both the keys and values, and then display them by appending the values in a list item (li). Currently, my attempt at this looks like: for (var i = 0; i < localStorag ...

Having the most recent versions of Chrome driver and slf4j dependencies did not solve the issue of creating an Appium driver session

After installing the latest Chrome driver, I was able to fix the issue that others have encountered with the same error. This is my first time using Appium. Below is the error message: Exception in thread "main" org.openqa.selenium.SessionNotCre ...

Creating a direct connection between a parent node and all of its children in OrgChartjs

Can I connect all children directly to one parent in Balkan OrgChart.js? This is my starting point based on the documentation of OrgChart.js. window.onload = function () { OrgChart.templates.family_template = Object.assign({}, OrgChart.templates.ana); ...

Unable to locate the Selenium server

After setting up the latest Selenium Standalone Server (3.0.0-beta2) on my Windows Server 2012 R2 Standard machine, with Java version "1.8.0_101" installed, I ran into an issue. Despite executing the JAR file using the command: java -jar selenium-server-s ...

Retrieve a collection of objects from JSON using Gson

How can I parse a json array using Gson? My json string contains an array of objects (filters array) along with other objects and fields. Here is the structure of my json file: { name: "test json", test_ob: { name: "test" }, filters [ { ...

Extracting Vertices, Edges, Faces, and Triangles from GLB Model Using ThreeJS GLTFLoader

I am looking to incorporate basic information about the model into my model viewer. Specifically, I need to obtain the vertex, edge, face, and triangle count of the object, or at the very least, the vertex count. My attempted approach involves using the f ...

E/Volley: [126] BasicNetwork.performRequest: Received an unexpected HTTP error with code 500

Why do I get the error "E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 500" when I click on the "login" button? Note: It works locally with a local database. This is my code: config.java: public class Config { //URL to our lo ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Incorporating an HTML page into a dialog using AngularJS: A step-by-step guide

Is it possible to dynamically change the content of a dialog by updating the URL? I have multiple HTML pages that I want to display in my dialog by simply changing the URL. <md-button ng-click="showDialog($event,'myurl/page-1.html')">Show ...

having difficulty transmitting parameter to angular directive

After assigning a collection to a source variable, I am trying to activate a third party control (bootstrap-select) using a directive that watches the assigned collection. angular .module('app').directive('bootstrapDropdown', ['$t ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Instead of printing only the JSON data using "response.data", the entire response is being printed out

I'm making a GET request from an AngularJS 1.5x client to a Java HTTP method. In the client, I want to display the response that includes some JSON data. // This is a method from an Angular service that sends AJAX requests this.getTask = function(tas ...

Fetching data from a server using Angular and displaying it in controllers

I am currently working on a project where I need to retrieve JSON files and their content using a factory in AngularJS. My main goal is to make this data accessible to other controllers, but I am struggling with getting the factory to return the deityData. ...

Can you explain the significance of the regular expression pattern /(?:^|:|,)(?:s*[)+/g in Javascript?

When it comes to Jquery, the regexp pattern is defined as follows: var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; This particular pattern is designed to match strings such as "abc,[" and "abc:[", while excluding instances like "abc^[". But what doe ...

Discover the inner workings of the code below: set a variable called "start" to the current time using the new Date().getTime() method. Create a loop that continuously checks if

I'm having trouble understanding how this code snippet works. Can someone please provide a demonstration? Thanks in advance.... It seems that the code is subtracting 'start' from the current date with new Date, resulting in 0 which is less t ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...