How to find Elements in a Webpage using JavaScript in Selenium?

SeleniumAutomation TestingTesting Tools

We can find elements in a web page with the help of JavaScript. We can also validate the elements returned by the JavaScript methods in the browser Console (Pressing F12). JavaScript methods to find elements are −

getElementsByTagname

To obtain a collection of elements with the matching tagname passed as parameter to the method. If there are no matching elements, an empty collection is returned.

Syntax

document.getElementsByTagName("<name of tag>")
To get the first matching element,
document.getElementsByTagName("<name of tag>")[0]

getElementsByName

To obtain a collection of elements with the matching value of name attribute passed as parameter to the method. If there are no matching elements, an empty collection is returned.

Syntax

document.getElementsByName("<value of name attribute>")
To get the first matching element,
document.getElementsByName("<value of name attribute >")[0]

getElementsByClassName

To obtain a collection of elements with the matching value of class attribute passed as parameter to the method. If there are no matching elements, an empty collection is returned.

Syntax

document.getElementsByClassName("<value of class attribute>")

To get the first matching element,

document.getElementsByClassName("<value of class attribute >")[0]

getElementId

To obtain an element with the matching value of id attribute passed as parameter to the method. It normally yields a single element since the value of the id attribute is unique in a page.

If there is no matching element, null is returned.

Syntax

document.getElementById("<value of id attribute>")

querySelector

To obtain an element with the matching value of css expression passed as parameter to the method. If there is no matching element, null is returned.

Syntax

document.querySelector("<css expression>")

raja
Published on 03-Apr-2021 10:33:27
Advertisements