Nancy Cruz
Nancy Cruz

Reputation: 125

Selenium c# how to findElement by JavaScript?

I'm working with an old portal and I have to use IE. There are some things that it doesn't find, cause it's part of a <td> menu, I tried to find it by XPath, but doesn't help.

I found the form is being rendered by a JavaScript function. And I'd like to click on them just to execute it, but how can I locate the page elements using selenium WebDriver??

For example: if I had this code

<div class="logout-link ng-scope" 
     ng-click="login(&quot;github&quot;)" 
     ng-show="!me" ng-controller="MenuCtrl">login</div>

How can I execute the ng-click part with the Selenium WebDriver?

Upvotes: 2

Views: 2799

Answers (3)

Saurabh Gaur
Saurabh Gaur

Reputation: 23805

Why do you want to execute Javascript to locate an element??? Try using WebDriverWait to wait until element visible and clickable as below :-

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

var Login = wait.Until(ExpectedConditions.ElementToBeClickable(By.Xpath("//div[text() = 'login']")));
 Login.Click();

Note :- make sure before try this element is not inside any frame

Hope it helps.....:)

Upvotes: 0

rg702
rg702

Reputation: 92

Clicking on the web element you create executes the associated function. Look via CSS Selector against the ng-click:

IWebElement elem = driver.FindElement(By.CssSelector("div[ng-click=login(&quot;github&quot;)]"));
elem.click();

You could also build an action to move to the element and then click on it:

IWebElement elem = driver.FindElement(By.CssSelector("div[ng-click=login(&quot;github&quot;)]"));
Actions action = new Actions(driver);
action.MoveToElement(elem).Click().Build().Perform();

Upvotes: 0

Mikhail
Mikhail

Reputation: 665

  1. Make sure you're trying to find element in the same frame it is located. Answer example: How to switch between frames in Selenium WebDriver using Java
  2. Try to wait for element to appear and be available: http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
  3. Hopefully you know how to find elements via JS (document.getElementsByClassName('logout-link ng-scope')) and here is answer on hot to use JS in C#: Execute JavaScript using Selenium WebDriver in C# - only difference is that you don't need to return anything - you only need to '.click()'

Upvotes: 1

Related Questions