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

Understanding the scope within a .when .done function in jQuery

I'm currently grappling with accessing a variable from within a .when.done function. Take a look at this illustrative example: var colviews = { 1: true, 2: true, 3: false } $.when( $.getScript( "/mckinney_images/jquery.tablesorter. ...

I'm thinking about transitioning my current React app to Next.js. Do you think it's a good move?

We have recently transitioned our project from react-redux with firebase authentication and solr DB to next.js. Below is the updated folder structure of our app: --src --actions --assets --components --controllers --firebase --redu ...

What sets apart the `ajax:send` event from the `click` event is that it specifically triggers an ajax

Currently, I am utilizing ajax requests with coffee in my Rails project as shown below. $('#reload').on( 'click': -> $('#response').html "<div class='panel'><img src='assets/load.gif'/> ...

Creating a Java application to append an array to a preexisting object in a mongoDB database

I have been working on a program that enables users to input information about a team, including the team name, size, and player details. While the code is functional, it does not behave as desired. My goal is to store an array of "players" and add data to ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

When executing a JavaScript program, an error with the message 'MODULE_NOT_FOUND' appeared, causing the internal module loader in Node to throw an error at line 1145

node:internal/modules/cjs/loader:1145 throw err; ^ Error: Module 'C:\Users\sande\3D Objects\JavaScript-Lesson\lesson08.js' not found at Module._resolveFilename (node:internal/modules/cjs/loader:1142:15) at Mo ...

Advanced jQuery Autocomplete with Nested Ajax Requests

I am currently developing a feature that allows users to search for albums using the Spotify Metadata API. The main functionality is working well, but I'm running into an issue with retrieving album cover art when making nested calls. This seems to be ...

What is the best way to pinpoint a specific Highcharts path element?

I am currently working on drawing paths over a graph, and I am looking to dynamically change their color upon hovering over another element on the page - specifically, a list of data points displayed in a div located on the right side of my webpage. Below ...

Concealing buttons and Enabling others using ajax

I am facing a situation where I need to modify the behavior of a modal window on my webpage. The modal currently has two buttons for confirmation and cancellation, as shown in the code snippet below. Inside this modal, there is a <div class = "resp"> ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

Turn off HTML5 Audio

There are 4 <audio> elements on a webpage. The client has asked for them to be available sequentially. Meaning, the first audio should play, then the rest should remain disabled until the first one finishes, and so on. In addition, they want the au ...

Using Vue.js to dynamically update values in JavaScript code or tags

I've encountered an issue that I'm having trouble articulating, but I'll do my best to explain. Upon loading the page, the following code snippet, which uses jinja-based placeholders, is executed: <div class="ui container"> ...

Issue with Angular Swiper carousel: Error message pointing to node_modules/swiper/angular/angular/src/swiper-events.d.ts

I am attempting to implement a carousel in Angular using Swiper (). An error message is appearing: Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not meet the constraint ...

Troubleshooting problem with input fields in Protractor due to sendKeys malfunction

My current task involves automating end-to-end tests using Protractor on an Angular application. However, I've encountered an issue with sending keys to input fields. The sendKeys function consistently misses a few characters each time it is used, so ...

Tips on showcasing array elements within a table's tbody section and including several values within the same array

I am struggling to figure out how to display array values in my table rows that I receive from input values. I have created an array, but I can't seem to find a way to display them in the table. Furthermore, I want to be able to add more values to th ...

What's the scoop on NodeJS, Express, Nginx, and Jade?

Currently exploring options for technologies and libraries to use in a new, large-scale project. With knowledge of NodeJS, JavaScript, Express, and Jade (now Pug), my team and I are leaning towards adopting these for the project. The main issue we're ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...