- 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 to obtain the tagname of the parent element in Selenium webdriver?
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.
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
To Continue Learning Please Login
Login with Google