2017-02-16 48 views
0

我正在遍歷頁面上的所有div,其類名爲.label-tel。當我循環他們時,我如何抓住下一個兄弟姐妹?在CSS中,我只會使用.label-tel + .tel。但由於div.label-tel目前在一個對象,我不知道如何完成。在JavaScript中,我如何獲得我設置爲對象的div的兄弟?

這是我試過的,但沒有奏效。

document.querySelector(phone + " + .tel"); 

這是我的完整代碼。

的JavaScript

let phoneList = row.querySelectorAll("div.label-tel"); 
for (let phone of phoneList) { 
    document.querySelector(phone + " + .tel"); 
} 

HTML

<div class="label label-tel">Work phone:</div> 
<div class="tel">352.342.1460</div> 

<div class="label label-tel">Mobile phone:</div> 
<div class="tel">352.942.1990</div> 
+0

爲什麼你用 '的(讓PHONELIST的手機)',而不是對 '(讓PHONELIST電話)'? – Julsy

+0

@Xufox那麼querySelector會不會是'javaScript object + string'?如果'phone'已經是您想要找到兄弟的對象,爲什麼不只是'phone.nextElementSibling'? – Santi

+2

phone.nextElementSibling – juvian

回答

1

下面是使用以前評論nextElementSibling的一種方式。

var row = document.getElementById('row'); 
 
const phoneList = row.querySelectorAll("div.label-tel"); 
 
const res = document.getElementById('results'); 
 

 
for (let phone of phoneList) { 
 
    var num = phone.nextElementSibling.textContent; 
 
    res.innerHTML += '<p>' + num + '</p>'; 
 
}
<section id='row'> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
    <div class="label label-tel">Work phone:</div> 
 
    <div class="tel">352.342.1460</div> 
 
</section> 
 
<hr> 
 
<div id='results'></div>

相關問題