What is the best way to highlight text with a blue background using selenium webdriver, resembling the action of dragging the mouse over the text?

Within my HTML code, there is an element that looks like this:

<td title="11607" style="text-overflow:ellipsis;white-space:nowrap;">11607</td>

To locate this element, I use the following locator:

string number= "11607";
IWebElement element = DriverUser.FindElement(By.XPath(string.Format("//*[contains(text(),'{0}')]" , number)));

My goal is to highlight the text 11607 using Selenium WebDriver.

After exploring various solutions, I came across two options. The first solution seemed promising initially but did not yield the desired result. I am unsure if the issue lies with the fact that the HTML tag is TD or if the solution itself is flawed. The second solution worked, but I believe there is room for improvement.

Here are the details:

  1. The first solution is: (taken from Highlight text using Selenium)
public static void HighlightText(this IWebElement element)
        {
            element.Click();
            Actions actions = new Actions(Driver);
            actions.SendKeys(Keys.Home).Build().Perform();
            int length = element.Text.Length;
            actions.KeyDown(Keys.LeftShift);
            for(int i = 0 ; i < length ; i++)
            {
                actions.SendKeys(Keys.ArrowRight);
            }
            actions.KeyUp(Keys.LeftShift);
            actions.Build().Perform();
        }

However, when I executed this solution, it had no effect.


Could it be due to the TD tag instead of an INPUT tag?

  1. The second solution is: (taken from , and found elsewhere)
        public static void HighlightTextJS(this IWebElement element)
        {
            var jsDriver = ( IJavaScriptExecutor ) Driver;
            string highlightJavascript = @"$(arguments[0]).css({ ""background"" : ""DodgerBlue""});";
            jsDriver.ExecuteScript(highlightJavascript , new object[] { element });
        }

This solution highlights the entire background of the element rather than just the letters. I am seeking a way to accurately simulate dragging a mouse cursor over the text.

Based on the provided screenshot The current outcome resembles the first line (11604), but I desire a visual similar to the second row (11602)

https://i.sstatic.net/ha9Vh.png



Is there a CSS property I can leverage to achieve this effect?




In addition, I attempted sending keys using SendKeys as follows:

Actions actions = new Actions(Driver);
                actions.MoveToElement(element);
                actions.SendKeys(Keys.Shift + Keys.ArrowLeft + Keys.ArrowLeft + Keys.ArrowLeft + Keys.ArrowLeft);
                actions.Build().Perform();

and also tried:

 Actions actions = new Actions(Driver);
                actions.SendKeys(element, Keys.Shift + Keys.ArrowLeft + Keys.ArrowLeft + Keys.ArrowLeft + Keys.ArrowLeft);
                actions.Build().Perform();

Unfortunately, these attempts were unsuccessful.

Thank you for any assistance provided!

Answer №1

Here is the C# code snippet that should be helpful.

new Actions(Driver).MoveToElement(element, 0, 0).ClickAndHold().MoveToElement(element, element.Size.Width, 0).Release().Perform();

Your initial approach started from the center of the element and moved to calculate the width from the center. The correct method should begin from the top left corner of the element and move until reaching the width of the element.
Hopefully, this solution works for your needs.

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 method for retrieving a single DataRow object from an Asp Web API?

Currently, I am in the process of developing Asp.Net WebApi code that needs to connect with some outdated C# back-end code where model classes are not utilized. Instead, pure dataTable is returned from DataAccess (I know, it sounds crazy) Below is the cod ...

Dividing and arranging dropdown list items into two columns using Bootstrap - An easy guide

How can I split a dropdown ul>li list into two columns using Bootstrap? I am attempting to divide the ul>li into two columns, with one aligning to the left and the other to the right. This is how I am currently doing it: <div class="btn-group" ...

Angular allows you to pass an array of objects as FormData items

Is there a way to send FormData with an array of objects to an API? I have attempted the following: https://i.stack.imgur.com/BlYby.png This is the request payload. How can I retrieve all items with other data from my .NET Core C# API? public class Back ...

On mobile devices, a height of 100vh exceeds the visible screen area

Struggling to cover the entire visible part of the browser window using 100vh due to issues on certain devices and mobile browsers. For example, in Safari, the URL section hides a top part, and similarly on some Android devices using Chrome. https://i.stac ...

Including an embedded iframe in an asp.net web form

I need to integrate an iframe into a web form by retrieving the URL from an API call to a third-party payment service. I am working with ASP.NET 4.5 and C# 6.0. The code for my web form includes implementing an iframe similar to that in an ASP.NET MVC cod ...

asp.net mvc action method not receiving JSON data

Trying to send data to a controller from client-side script, the data is being stringified resulting in the following format: {"Name":"","Description":"","FieldType":"radio","Fields":[{"Field":{"Name":"something","Value":"nameit"}},{"Field":{"Name":"somet ...

Utilizing Scenario Outlines in Specflow with Selenium using C#

I have a challenge with using a scenario outline in Specflow to generate tests based on the examples I provide, which I then need to execute using selenium and C#. The feature I've created looks like this: Scenario Outline: Login Given I have navigat ...

Not able to gather all the items through scraping

Despite using selenium and scrapy, I'm only able to retrieve 12 out of 487 items for scraping. I am struggling to determine where the issue lies. Any assistance in getting all the items scraped would be greatly appreciated. URL MY CODE: import scrap ...

Convert XML document to BSON format in C# programming language

Looking to transfer data from an XML file to BSON, and then import it into MongoDB using C#. Any suggestions on how to achieve this conversion process smoothly? ...

Locate a label based on its name and update the text of the label using code in

Help! I am trying to set label text from code behind in my ASPX page. I have multiple labels like lbl2, lbl3, etc. <asp:LinkButton ID="btn1" runat="server" onclick="btn1_Click" > <img id="img1" runat="server" width="195" he ...

Is it possible to shift the div inline-block using the CSS :after selector?

I'm looking to adjust the placement of the disk icon so that it aligns more with the baseline of the text without increasing the vertical space between lines. Below is the CSS code I've worked on so far: .openPage:after { content: ' &a ...

Creating a mapping between an Entity and DTO that involves ICollection and IList

I am facing an issue with mapping in AutoMapper. I attempted to use the ForMember function, but I keep encountering errors related to mapping. How can I create a CreateMap for these Entities? I have created an AutoMapping class: public class AutoMa ...

Styling with Chemistry: CSS for Chemical Formulas

Is there a way to write multiple formulas in CSS, or is there an alternative method I should consider? I want to integrate these formulas on my quiz website for students to use. I came across some intriguing examples that could be useful: However, I am s ...

Dynamically generated pop-up modal based on verified user

Can anyone provide guidance on this issue? I am working on a login screen for two types of users: Suppliers and Admins. I need to implement a popup screen that appears only when a supplier logs in, prompting them to sign a declaration by clicking on a rad ...

Each time I load the page, it displays differently depending on the browser. I'm struggling to understand the reason

Trying to figure out how to make the navigation bar close when a link is clicked and directed to a section instead of a new page. When on a large screen, I want the nav bar to remain open but automatically close when on a small screen (for example, when th ...

"Patience is key as you anticipate the loading of the ext-js dialog using

While running tests on an ext-js application using Selenium (WebDriver), I encountered an issue with a button that triggers a dialog to appear. The test proceeds to interact with form fields and buttons within the dialog, but Selenium executes these action ...

C# multi-threaded application experiences interface lock-ups

My c# .NET multi-threaded application is causing the interface to freeze in an unusual way. The freezing only occurs after the system sits idle long enough for the screen saver to start, prompting me to input my password to regain access. Once I successful ...

Choose the appropriate tests to execute using webdriver in a dynamic manner

As a tester specializing in automation, I have been exploring the use of WebDriver and pageObjects for running tests with NUnit. However, I am facing a challenge when it comes to executing tests in a predefined order. Our current GUI automation solution in ...

Populating dependent dropdown menus with database values while in edit mode

I'm struggling with filling dependent dropdowns. The dependent dropdowns work fine when entering data - I select a State from the dropdown and the dependent dropdowns reload based on that selection. The issue arises when I try to edit information. Th ...

Guide to drawing on a picturebox and saving it in Winforms using C#

   I am currently developing a basic graphic editor in Windows Forms (C#) with a PictureBox as my canvas. My goal is to include an "undo" feature while drawing using System.Drawing.Graphics. Here's where I am stuck: If I utilize picturebox.Crea ...