
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Parent HTML Tag with Selenium WebDriver in 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
Advertisements