Skip to content
Advertisement

What is the error OpenQA.Selenium.WebDriverException : javascript error: document.getElementByName is not a function

I got a error in executing the below line of code

driver = new ChromeDriver(@"C:UsershpDocumentsDriver");
driver.Navigate().GoToUrl("http://demo.guru99.com/v3/");
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementByName('uid').value ='mngr303517'");
js.ExecuteScript("document.getElementByName('password').value='ujudysY'");
js.ExecuteScript("document.getElementByName('btnLogin').click()");

I got the error At line 3

document.getElementByName is not a function (Session info: chrome=87.0.4280.141)

what is the reason for it?

Advertisement

Answer

The JavaScript method is document.getElementsByName(…) (plural – Elements not Element).

This method returns a collection of elements, not a single element.

js.ExecuteScript("document.getElementsByName('uid')[0].value ='mngr303517'");

Be sure to access the [0] index of the collection before calling the value property.

It might be a little cleaner to use document.querySelector instead:

js.ExecuteScript(@"document.querySelector(""[name='uid']"").value ='mngr303517'");
js.ExecuteScript(@"document.querySelector(""[name='password']"").value='ujudysY'");
js.ExecuteScript(@"document.querySelector(""[name='btnLogin']"").click()");
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement