2016-07-04 3 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> 

私は唯一のタイトル3で「spanタグ」にアクセスしようとしている私は、IDを指定することによって、それを行うことができます知っています。しかし、私が一般的に(つまりすべての要素に対して)したい場合はどうでしょうか。だから私の最初のアプローチは "私はdiv内のスパンタグを探します"でなければなりません。しかし私はそれをする方法を知らない?助けてください。

+1

私の答えをチェックしてください。実際には、 '特定のクラス名を持つ子 'と言ったように正しく理解しているかどうかはわかりませんが、' HTML'では指定されたクラス – Andersson

答えて

1

XPathをお試しください:

DIV3でスパンを選択するためにjqueryのセレクタを使用して
//div/span[text()="Title 3"] 
0

$("#div3 span") 

的または特異的にDIV3内の最初のspan要素:

$("#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; 
     } 
    } 

はそれがお役に立てば幸いです。

関連する問題