James
James

Reputation: 13

How to select a nested webelement in html?

I would like to retrieve a webelement out of a nested html path using either css selectors or xpath. My specific use case is that I would like to select the i element in the following snippet:

<td class="headerActionsTd" data-rolename="Speaker">
  <div class="headerActions">
    <span class="addNewParticipantSection">
      <i class="icon fa fa-user-plus" title="Add New"></i>
      </span>

How do I obtain the i webelement for this using either css selector or xpath?

Upvotes: 0

Views: 248

Answers (4)

bluegreener
bluegreener

Reputation: 16

Another option is that you can attempt to locate elements inside other elements. For example, you could store the addNewParticipantSection div in a WebElement, then use that WebElement's findElement method to locate the i element within it. Like so:

WebElement section = driver.findElement(By.className("addNewParticipantSection"));
WebElement icon = section.findElement(By.tagName("i"));
icon.click();

Upvotes: 0

Rajagopalan
Rajagopalan

Reputation: 6064

Since you said data-role only changes in the comment of the other person, here is the xpath you can use

"//td[@data-role='Speaker']//i"

Or

"//td[@data-role='Speaker']/div/span/i"

Upvotes: 0

cruisepandey
cruisepandey

Reputation: 29362

A simple one would be this :

CSS_SELECTOR

i.icon.fa.fa-user-plus[title='Add New']  

Note that, if there is multiple element with this css selector, then you have this facility to differentiate between them:

:first-child  
:nth-child(n)  
:nth-last-child(n)     

More can be found at this link

XPATH : would be :

//td[@data-rolename='Speaker']/descendant::span[@class='addNewParticipantSection']/i

Hope that helps.

Upvotes: 1

dangi13
dangi13

Reputation: 1275

Use this xpath: //td[@data-rolename='Speaker']//div//span//i[@title='Add New'] or
css : div.headerActions i

driver.findElement(By.cssSelector("div.headerActions i"));

for multiple elements :

List<WebElement> users = driver.findElements(By.xpath("//td[@data-rolename='Speaker']//div//span//i[@title='Add New']"));

Upvotes: 1

Related Questions