- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I get a parent HTML Tag with Selenium WebDriver using Java?
We can get a parent HTML tag with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the parent with the findElement(By.xpath()) method.
We can identify the parent from the child, by localizing it with the child and then passing (parent::*) as a parameter to the findElement(By.xpath()). Next to get the tagname of the parent, we have to use the getTagName() method.
Syntax
child.findElement(By.xpath("parent::*"));
Let us identify tagname of parent of child element li in below html code−
The tagname of the parent should be ul.
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ParentTagname{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement p=driver.findElement(By.xpath("//li[@class='heading']")); //identify parent from child element WebElement t= p.findElement(By.xpath("parent::*")); //getTagName() to get parent element tag System.out.println("Parent tagname: " + t.getTagName()); driver.close(); } }
Output
- Related Articles
- How do I set the Selenium webdriver get timeout?
- Get page title with Selenium WebDriver using Java.
- How to get selected option using Selenium WebDriver with Java?
- How can I close a specific window using Selenium WebDriver with Java?
- How do I get current URL in Selenium Webdriver 2 Python?
- How do I open Chrome in selenium WebDriver?
- Get HTML Source of WebElement in Selenium WebDriver using Python.
- How to get selected option using Selenium WebDriver with Python?
- How to scroll down using Selenium WebDriver with Java?
- Switch tabs using Selenium WebDriver with Java.
- How to scroll a specific DIV using Selenium WebDriver with Java?
- How do I resolve the ElementNotInteractableException in Selenium WebDriver?
- How can I get Webdriver Session ID in Selenium?
- How to type in textbox using Selenium WebDriver with Java?
- How to handle authentication popup with Selenium WebDriver using Java?

Advertisements