2016-07-04 167 views
0

是否可以知道父母是否包含具有特定類名的子標籤。 示例代碼檢查父標籤內的子標籤

<div id="parent_tag"> 
    <div id="div1"> 
     <span>Title 1</span> 
    </div> 
    <div id="div2"> 
     <b>Title 2</b> 
    </div> 
    <div id="div3"> 
     <span>Title 3</span> 
    </div> 
</div> 

我試圖訪問「span標籤」只有標題3.我知道我可以通過指定ID做到這一點。但是如果我想要它一般(即所有元素)。所以我的第一個方法應該是「我會在div內尋找span標籤」。但我不知道該怎麼做?請幫忙。

+1

檢查我的答案,但實際上我不確定是否正確理解了你的說法,正如你所說的'具有特定類名的子類',但在提供的'HTML'中沒有指定類的元素... – Andersson

回答

1

嘗試XPath

//div/span[text()="Title 3"] 
0

使用jQuery選擇在DIV3選擇跨度:

$("#div3 span") 

或特定第一span元素裏面DIV3:

$("#div3 span:first") 
0

這裏的想法得到你需要的東西

// Get Parent Element 
    WebElement parent = driver.findElement(By 
      .xpath("//div[@id='parent_tag']")); 

    // Get All children elements of the parent element 
    List<WebElement> children = parent.findElements(By.xpath("//*")); 

    // Init some based param for next usage 
    boolean checkClass = false; 
    String expectedClass = "Expected_Class"; 

    // Fetch each child element and check whether its text contains expected string. 
    for (WebElement child : children) {  
     if (child.getAttribute("class").contains(expectedClass)) { 
      checkClass = true; 
     } 
    } 

    if (checkClass) { 
     System.out 
       .println("We have at least one child has expected class: " 
         + expectedClass); 
    } 
    else System.out.println("We don't have any child has expected class: " 
         + expectedClass); 

如果要檢查的文本,我們可以做

if (child.getText().contains(expectedText)) {   
      checkResult = true; 
     } 
    } 

希望它能幫助。