2017-02-12 61 views
0

我正在使用webdriverjs,並且我想獲取webelement的父id。有多個稱爲行的類,但每個都有不同的id。挑戰是在發送消息時生成ID。所以我可以通過類抓住innerHtml,然後嘗試獲取Id。 我有以下HTML,如何使用JavaScript selenium獲取父div ID?

<div class="row" id="4003"> 
<div class="client-chat"> 
<p class="client-chat-text">If you have any questions, don’t hesitate to message me. I’m here to help with whatever you need!<span class="chat-time">Feb 01 2017 11:30:57</span></p> 
</div> 
</div> 

<div id="4361" class="row"> 
<div class="coach-chat"> 
<p class="coach-chat-text"> 
hi 
</p> 
</div> 

即用ID(4361)是生成的一個,我需要搶我的測試中第二個div。不過,我可以取coach-chat-text。我如何獲得硒中的父元素。我已經嘗試了下面的代碼,但我不知道如何獲取父ID。

it('send a text message now',function(done){ 
      driver.findElement(webdriver.By.css("#messageField")).sendKeys('Hi'); 
      driver.sleep(1000); 
      driver.findElement(webdriver.By.xpath(".//*[@id='sendMessage']")).click().then(function(){ 
       driver.findElement(webdriver.By.className("coach-chat-text")).getText().then(function(text){ 
        var message = text.slice(0,2); 
        //i want to fetch the parent id here. 
        try { 
         expect(message).to.equal("www.pluma.co"); 
         done(); 
        } catch (e) { 
         done(e); 
        } 
       }); 
      }); 
     }); 
    }); 

回答

0

如果使用webdriver.By.xpath與類的查找元素「教練聊天文本」,那麼你可以使用XPath家長選擇 - /parent::node() - 尋父元素。

像下面這樣,雖然你的XPath可能會有所不同:

driver.findElement(webdriver.By.xpath(".//*[contains(@class, 'coach-chat-text')]/parent::node()"));