NarendraR
NarendraR

Reputation: 7708

How to set an attribute value using JavascriptExecuter in Selenium WebDriver

I am trying to set an attribute value for all same kind of <img> tag in My website e.g

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

and i wanted to set style="display:none" so I will be able to hide them.

I have tried 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 getting an error

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

Is any one help what is wrong here or what other I can do?

Upvotes: 0

Views: 3644

Answers (3)

Saurabh Gaur
Saurabh Gaur

Reputation: 23815

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

You are using JavascriptExecutor to execute javascript on an element but syntactically incorrect, in executeScript arguments will be made available to the JavaScript via the arguments magic variable, as if the function were called via Function.apply where arguments must be a number, a boolean, a String, WebElement etc.

You can try as below :-

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);
  }
}

Upvotes: 1

Guy
Guy

Reputation: 50899

You use document to locate the WebElement. In your case you already located it. Try

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

Upvotes: 0

Hrabosch
Hrabosch

Reputation: 1583

There is problem with that you pass e like a object and there is called toString(), so final result is with [] etc... Another way could be 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 wrote it without test, so maybe you should edit it ;)

Upvotes: 1

Related Questions