How to obtain the tagname of the parent element…
We can obtain the tagname of the parent element in 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 the parent of child element li in the below html code −

The tagname of the parent should be ul.
Example
Code Implementation.
package RK1.Building_a_selenium_project;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ParentTagName {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "F:\\Work Environment\\MyProject\\chromedriver.exe");
WebDriver wd = new ChromeDriver();
String url = "https://www.tutorialspoint.com/about/about_careers.htm";
wd.get(url);
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement p=wd.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());
wd.close();
}
}
Output
Starting ChromeDriver 104.0.5112.79 (3cf3e8c8a07d104b9e1260c910efb8f383285dc5-refs/branch-heads/5112@{#1307}) on port 16278
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Aug 19, 2022 3:05:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Parent tagname: ul
1 COMMENT
Your article helped me a lot, is there any more related content? Thanks!