问题
i am trying to click on an element for which style is style="display: block;" but not able to to do so.
below is the html
code
<div class="fl f18 dtoggler pointer underline some-padding new_data_entry" data-div-id="eBWJcg" data-div-ref="new_Passport_form.eBWJcg">+ Add Passport</div>
<div class="clear new_Passport_form qEgULQ some-margin togglable" style="display: none;">
Selenium
code:
driver.get("idfystaging.com/users/sign_in");
driver.findElement(By.name("user[login]")).sendKeys("rustam1@yopmail.com");
driver.findElement(By.name("user[password]")).sendKeys("Password123");
driver.findElement(By.name("commit")).click();
driver.switchTo().frame("upload_iframe_1");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.ESCAPE);
JavascriptExecutor executor= (JavascriptExecutor)driver;
executor.executeScript("document.getElementById('qEgULQ').style.display='block';");click();
Error log:
Cannot read property 'style' of null.
回答1:
qEgULQ
is class, not id. Try
executor.executeScript("document.getElementsByClassName('qEgULQ').style.display='block';");
回答2:
You're trying to apply Javascript
to element with id="qEgULq"
while you need element with class="qEgULq"
:
Just replace
executor.executeScript("document.getElementById('qEgULQ').style.display='block';");
with
executor.executeScript("document.querySelector('div.clear.new_Passport_form.qEgULQ.some-margin.togglable').style.display='block';");
Also note that your click();
from provided piece of code doesn't bound to element
Update
If some of class names are generated dynamically or assigned just on some events, you can avoid using class names as locator:
WebElement targetDiv = driver.findElement(By.xpath("//div[text()='+ Add Passport']/following-sibling::div"));
executor.executeScript("arguments[0].style.display='block';", targetDiv);
来源:https://stackoverflow.com/questions/42526292/clicking-on-an-style-display-block-in-selenium-webdriver