I have used most of the element locators while testing with Selenium, but very low frequently used the 'TagName' locator. Please give an example.
4 Answers
Now supposing, a software web element does not have any ID or Class Name, then how can we locate that element in Selenium WebDriver? The answer is there are many alternatives of the Selenium WebDriver element locators and one of them is locating an element by tag name.
Locating an element by tag name is not too much popular because in most of cases, we will have other alternatives of element locators. But yes, if there is not any alternative then you can use the element's DOM tag name to locate that element in webdriver.
Here you can select the tagname as a locator like:
// Locating the element by tagName and store its text in variable 'dropdown'.
String dropdown = driver.findElement(By.tagName("select")).getText();

- 30,738
- 21
- 105
- 131

- 413
- 2
- 11
-
Using it to find an `IFRAME` or maybe `A` tags to get all the links on the page are more likely to be more widely used. – JeffC Dec 06 '15 at 14:56
Thanks to the deprecation of By.tagName you should use By.css for Shah's answer...
String dropdown = driver.findElement(By.css("select")).getText();

- 30,738
- 21
- 105
- 131

- 3,067
- 6
- 20
- 54
-
What programming language? [Java](https://en.wikipedia.org/wiki/Java_%28programming_language%29)? – Peter Mortensen Nov 13 '22 at 23:27
-
Is it actually `By.css`? Not [`By.CssSelector`](https://www.selenium.dev/documentation/webdriver/getting_started/upgrade_to_selenium_4/#tabs-1-2)? – Peter Mortensen Nov 13 '22 at 23:46
We use the actual name of the tag like <a> for anchor and <table> for table and input for <input>. This helps to get all the elements with a given tag name.
Example: to select the first element of a given input
var dialog = driver.FindElement(By.ClassName("ladialog"));
var save = dialog.FindElements(By.TagName("input"))[0];
save.Click();

- 30,738
- 21
- 105
- 131

- 33
- 5
-
-
https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/by_exports_By.html#By.css – JGleason Dec 18 '18 at 15:33
Also importantly, the tagName
locating strategy can be used to get or fetch all the links on a webpage and print them to console. Try this:
// Get all links in a webpage
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Links count is: " + allLinks.size());
for(WebElement link : allLinks)
System.out.println(link.getText());

- 30,738
- 21
- 105
- 131
-
What programming language? [Java](https://en.wikipedia.org/wiki/Java_%28programming_language%29)? – Peter Mortensen Nov 13 '22 at 23:27