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 to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

This code snippet results in the property being unrecognized

I recently wrote this block of code and encountered an error while trying to run the alert function. It keeps telling me that 'this.words' is not defined. I suspect the issue lies within the jQuery portion, as I am able to access the array where ...

The operation could not be completed with exit code 1: executing next build on Netlify platform

Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

Ways of retrieving Sveltekit session data in an endpoint

Is there a way to access a session in an endpoint using SvelteKit? I attempted the following with no success: import { get } from 'svelte/store'; import { getStores} from "$app/stores"; function getUser() { // <- execute this du ...

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

When attempting to close the current window in Python, Windows Handling automatically shuts down the entire browser

Currently, I am using Windows handling to open the map directions in a new window. After the new window opens, I close it and continue with the remaining work in the code. However, instead of just closing the child window, the whole browser is being closed ...

The execution of certain functions in Python Selenium is contingent upon the output of the preceding function

I have a challenge where I need to check for the presence of element A or B on a page using Python. If it's element A, I want to run function A and if it's element B, I want to run function B. I'm thinking of using a dictionary and an "if" e ...

Why isn't cancelAll function available within the onComplete callback of Fine Uploader?

This is the completion of my task. $('#fine-uploader-house').fineUploader({ ... }).on('complete', function(event, id, name, jsonData) { if(!checkEmpty(jsonData.cancelAll) && jsonData.cancelAll){ //$(this).cancelAll(); ...

There seems to be an issue as req.files in Sails.js is blank and the value of req

I've been struggling with this problem for quite some time now. Despite my efforts to find a solution through Google and StackOverFlow, I have not been successful. The issue lies within a project I am working on, where I have implemented a "Product" M ...

Flask is failing to display AJAX data

Looking to embark on a Flask project involving sending an AJAX request. In the Flask code, I want to assign a variable to handle the request and display it on the page using a Jinja variable. Flask from flask import Flask,render_template,request app = Fla ...

Experiencing issues with ng-repeat in AngularJs?

I am currently facing an issue with two tables that are rendering data through AngularJS from two separate C# methods. Both tables have almost identical structures, with the first one being used as a search field and the second one to display names. The pr ...

Using dynamic jquery to target specific elements. How can we apply jquery to selected elements only?

Hello everyone! I have been working on a simple hover color change effect using jQuery, but I noticed that I am repeating the code for different buttons and service icons. Is there a way to achieve the same result so that when a button is hovered, the co ...

Dissipating visuals / Effortless website navigation

Do you have experience working with HTML or are you looking for specific code examples? I've noticed some websites with sliders that feature clickable images fading in as soon as the page loads. I tried searching for information on how to achieve thi ...

Update the current value in array.prototype

Recently, I've noticed that the built-in JavaScript sort function can be unreliable at times. To address this issue, I decided to create my own sorting function. Consider the following scenario: Array.prototype.customSort = function(sortFunction, upd ...

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

What could be the reason for the selection box in my form not changing the items when togg

I'm having an issue with my form selection box code that used to work but is now not functioning properly. Could someone please help me identify where the error lies? Essentially, I have a form with the ID #main and a select box named #chart-type. Th ...

Discovering elements based on text content instead of tags can be achieved by employing

HTML <div class="cell"> <!----> message. <!----></div> Attempting to create an XPath using text and then click on the specified element. My locator (//td[@class="el-table_1_column_5 el-table__cell"]//div[contai ...

Leverage JavaScript E4X to cleverly rename specific XML elements

Currently, I am using JavaScript to manipulate XML without involving the DOM in a browser context. I need assistance with creating an E4X expression that can rename a list of tags based on a given substring. The challenge is that I may not know the exact t ...

Issue encountered while attempting to set up react-native project

Whenever I attempt to create a new react-native project using the command: npx react-native init myproject I encounter the following errors: ERESOLVE is overriding peer dependency npm gives me a warning while trying to resolve: [email protected] ...

Executing the selenium-standalone npm package on a Linux-based Ubuntu server

After attempting to launch selenium-standalone on my Digital Ocean Ubuntu server, I encountered some difficulties. Upon logging into the server via SSH, these commands were executed: apt-get update apt-get install nodejs nodejs-legacy npm default-jre npm ...