简体   繁体   中英

js.executeScript doesn't work when using getElementsByClassName in selenium

I have a method:

public void delayToCapture(String methodGetBy, String key){
    /* List of methodGetBy:
     * 1. getElementById
     * 2. getElementsByTagName
     * 3. getElementsByClassName
     * 4. querySelectorAll
     */

    System.out.println("Excuteing javaScript...");              

    if(methodGetBy.equals("getElementById")){
        js.executeScript("setTimeout(function(){ document." +methodGetBy+ "('" +key+ "').setAttribute('style', 'display: none');},500);");
    }
    else if(methodGetBy.equals("getElementsByClassName")){
        js.executeScript("setTimeout(function(){"
                        + "var elems = document.getElementsByClassName('"+ key +"');"
                        + "for(var i = 0; i < elems.length; i++){"
                        + "elems[i].style.display = 'none';}"
                        + "},"
                        + "500);");
    }

}

And I call that method in another class:

delayToCapture("getElementsByClassName", "positionmenu");

When running the code, console always show me this message:

java.lang.NullPointerException

However, if I run this code at below on console of Brower directly -> It's work:

setTimeout(function(){
var elems = document.getElementsByClassName('positionmenu');
for(var i = 0; i < elems.length; i++){
elems[i].style.display = 'none';
}
},500);

So, could you tell me what is the reason here?

Try using this :

 else if(methodGetBy.equals("getElementsByClassName")){
        List<WebElement> element = driver.findElements(By.className(key));  // getting element using class name
        js.executeScript("setTimeout(function(){"
                        + "var elems = arguments[0];"
                        + "for(var i = 0; i < elems.length; i++){"
                        + "elems[i].style.display = 'none';}"
                        + "},"
                        + "500);", element);
    }

Hope that helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM