By.tagName( ) is generally used to locate all the elements with similar HTML tags.
As we know that all the hyperlinks on any page contains the html tag <a> in the HTML source code. For example - HTML source code of a Hyperlink:
<a href="http://www.google.com> Google </a>
Suppose if you want to locate and retrieve all the links on any page, you will have to use the follwing:
Here a represents the HTML anchor tag. So all the elements on the page having anchor tag 'a' in the HTML source code of the page will be retrieved using this statement.
We are going to retrieve all the Hyperlinks on the page using this statement in the next post. But for now lets work with the By.tagName( ) which locates only one web element. That is only one element on the page should have the Tag Name in its source code that we are going to specify.
Lets find such element having a unique Tag Name:
1. Open http://compendiumdev.co.uk/selenium/basic_html_form.html page
2. Right click on the page and select 'View Page Source' option as shown below:
3. Ensure that the HTML source code of the page is displayed as shown below:
4. Press Ctrl + F on your keyboard and search for <textarea in the Find Box as shown below:
5. From the above search, observe that only one tag is available in the source code with textarea name.
6. So textarea is the tag name of the Web Element which has a unique tag in HTML source code.
Locate the element having the unique tag name i.e. textarea using By.tagName( ) and enter the text into the located text area field as explained in the below screen:
Lets Implement the Test on Eclipse IDE:
1. Create a new Java Project say 'WebDriver-Project75' in Eclipse IDE
2. Configure the Project to work with Selenium WebDriver
3. Create a package say 'package75' under the newly created project.
4. Create a Java Class file say 'Class75' under the newly created package as shown below:
1. Write the following code into the newly created Java Class file as shown below and make sure that you resolve all the errors before going to next step:
2. Create a test method 'byTagNameDemo( )' which contains the following code as shown below:
7. Save and Run the 'Class75.java' file by selecting the 'JUnit Test' option and ensure that our Automation Test has located the text area field using the specified tag name, cleared the text area field and entered the text 'Hello' as shown in the below video:
Watch the below video:
Click here to watch the video.
Download this Project:
Click here to download this project and import into Eclipse IDE on your machine.
Please comment below to feedback or ask questions.
Using findElements( ) will be explained in the next post.