Guide on setting an attribute value with JavaScriptExecutor in Selenium WebDriver

I am attempting to set an attribute value for all instances of the same type of <img> tag on My website, for example:

<img src="images/temp/advertisement.png">

and I want to set style="display: none" so that I can hide them.

I have tried the following method -

List<WebElement> element = driver.findElements(By.tagName("img"));

    for(WebElement e:element)
    {

        if(e.getAttribute(src).contains("images/temp/advertisement.png"))
        {
            jse.executeScript("document."+e+".setAttribute('style', 'display: none;')");
        }
 }

but I'm encountering an error

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token [

Can anyone help me figure out what is wrong here or suggest another approach?

Answer №1

There was a problem in the main thread: org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token [

The issue arises when using JavascriptExecutor to run javascript on an element, but there is a syntax error present. When executing with executeScript, the arguments will be accessed by JavaScript through the arguments magic variable, similar to calling the function via Function.apply. The types of supported arguments include numbers, booleans, strings, and WebElements.

To address this issue, consider the following approach:

List<WebElement> element = driver.findElements(By.tagName("img"));

for(WebElement e:element) {    
  if(e.getAttribute("src").contains("images/temp/advertisement.png")){
       jse.executeScript("arguments[0].style.display = 'none'", e);
  }
}

Answer №2

There seems to be an issue with passing e as an object and utilizing the toString() method, resulting in output like []. An alternative approach could look something like this:

jse.executeScript(
        "var imgs = document.getElementsByTagName('img');" +
        "for(var i = 0; i < imgs.length; i++) { " +
        "    if (imgs[i].getAttribute('src').indexOf('images/temp/advertisement.png') != -1) { " +
        "       imgs[i].setAttribute('style', 'display: none;');" +
        "    }" +
        "}" );

I have not tested this code, so you may want to make some adjustments ;)

Answer №3

When finding the WebElement, remember to utilize the document. If you have already located it, attempt the following:

jse.executeScript("arguments[0].setAttribute('style', 'display: none;')", e);

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

Perform a bash command using PHP when an HTML button is clicked

Today, my brain seems to be on vacation. Currently, I have set up a Raspberry Pi with vlc running and connected to a mounted screen on the wall. There is a web page with simple controls to manage the pi, switch between different vlc streams, or stop stream ...

What is the best way to establish communication between a server and client using sockets in Node.js?

Presently, I am in the process of developing a JavaScript application using AppJS. I'm encountering some difficulties understanding the communication between the client and server. Issue with Menu Bar and Socket Interaction The main challenge lies ...

unable to update the table due to issues with the knockout observableArray

My goal is to collect values from form fields and store them as an object in an observableArray. I want to display these objects in a table so that every time I hit the 'add' button, the table should be updated. However, I am facing issues with t ...

JavaScript drag functionality is jerky on iPads, not seamless

I am currently attempting to implement a feature where I can drag a div (#drag) within its parent container (#container) using only pure JavaScript. This functionality is specifically required to work on iPad devices only. After writing a script that func ...

The React server-side rendering isn't reflecting changes made on the client-side route

Upon the first refresh, both the server and client side are updated; however, subsequent updates only affect the client side when switching pages with react router. For instance, refreshing the page or entering a new URL causes changes on the server and t ...

What is the best way to query based on a nested object property in Mongoose?

const collection = [ { inner_obj: { prop: "A" } } ] Get the outer records by searching for the ones that match the value of the `prop` property within the `inner_obj` column. How can we locate the o ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...

Attempting to choose everything with the exception of a singular element using the not() function in Jquery

Within the mosaic (div #mosaique) are various div elements. My goal is to make it so that when I click on a specific div, like #langages or #libraries, the other divs become opaque while the selected div undergoes a size change (which works correctly in t ...

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

endless refreshing material ui accordion

Facing an issue with infinite rerender while trying to create a controlled accordion component using Material UI accordion. Here is the code snippet, any insights on why this could be causing an infinite rerender? const [expanded, setExpanded] = React.us ...

An error known as "cart-confirmation" has been encountered within the Snipcart platform

I am looking to integrate Snipcart checkout in my Next.js application. However, when I try to validate a payment, I encounter an error message: An error occurred in Snipcart: 'product-crawling-failed' --- Item 1 --- [Item ID] 8 [Item Unique ID] ...

Identical IDs appearing in multiple buttons causing a conflict

I am currently loading content from external HTML files, specifically page1.html and page2.html. Although everything is the same except for the pictures and text, I am encountering an issue with the close button. It only closes page1.html.Feel free to chec ...

Locating the save directory with fileSystem API

I've been working on saving a file using the fileSystem API. It appears that the code below is functional. However, I am unable to locate where the saved file is stored. If it's on MacOS, shouldn't it be in this directory? /Users/USERNAM ...

Using JavaScript to save a file with a data URL in Internet Explorer

Need help with file conversion on different browsers. I developed an app that converts files, and everything was working perfectly in Chrome. However, when it comes to IE (10/11/Edge), I'm facing some challenges: 1) The HTML5 download attribute does ...

Restrict the selection of dates in the jQuery UI datepicker by disabling public holidays, weekends, the next day after 10am, and only allowing Tuesday, Wednesday, and Thursday as

I found a code snippet on disabling weekends, public holidays, and the next day after 10 am using JQuery UI Datepicker. However, I'm facing an issue where I want to restrict selections to only Tuesday, Wednesday, and Thursday. // JavaScript logic for ...

Utilize Gson to precisely format double values up to 4 decimal places

Is there a way to use Gson to format double values so that they are rounded or truncated to 4 decimal places? ...

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

Creating a interactive navigation bar with External JSON data in HTML and JavaScript

Is there a way to create a dynamic MenuBar by using an external JSON file? How can I write HTML code to fetch and display JSON data dynamically? What is the process for reading a JSON file? //JSON File = Menu.Json {"data": [{"id": "1", "text": "F ...

Styling Your Navigation Bar with CSS and Active States

Creating an interactive navigation element for a menu can be challenging, but here's a helpful example. http://jsfiddle.net/6nEB6/38/ <ul> <li><a href="" title="Home">Home</a></li> <li class="activ ...