Java & Selenium: get parent HTML WebElement (tag) from current (child)

Trabla: Java & Selenium: get parent HTML WebElement (tag) from current (child)

Solving:

Use   xpath - "parent::*"

Example 1:

WebElement lvChildElement    = driver.findElement( By.id("id123") );

WebElement lvParentElement  =  lvChildElement.findElement( By.xpath("parent::*") );   

Example 2:

HTML

<div>
    <a href="http://mysite.com/post-1" > 
          <img width="100" height="200" 
              src="http://mysite.com/images/1.jpeg" 
              class="image-100x200" >
    </a>
</div>
<div>
    <a href="http://mysite.com/post-2" > 
          <img width="100" height="200" 
              src="http://mysite.com/images/2.jpeg" 
              class="image-100x200" >
    </a>
</div>

List<WebElement> lvImages = driver.findElements(By.className("image-100x200") );

for ( WebElement lvImage: lvImages ) 
{
       WebElement lvParentElement = lvImage.findElement(By.xpath("parent::*"));
 
        System.out.println( "URL : " + lvParentElement.getAttribute("href") );
}

-----------
output:
-----------
URL : http://mysite.com/post-1
URL : http://mysite.com/post-2

No comments:

Post a Comment