2017-06-02 54 views
0

我知道如何使用querySelectorAll爲特定類選擇。但是,我將如何選擇具有特定數據屬性的DOM對象。在數據屬性javascript上使用querySelectorAll(無jQuery)

例如:

<div class="person"> 
    <div class="detail" data-field="name">Tim</div> 
    <div class="detail" data-field="age">24</div> 
    <div class="detail" data-field="hair">black</div> 
</div> 
<div class="person"> 
    <div class="detail" data-field="name">Tim</div> 
    <div class="detail" data-field="age">34</div> 
    <div class="detail" data-field="name">red</div> 
</div> 
<div class="person"> 
    <div class="detail" data-field="name">David</div> 
    <div class="detail" data-field="age">56</div> 
    <div class="detail" data-field="name">brown</div> 
</div> 

如果我要選擇與特定類如「細節」

document.querySelectorAll('.detail') 

我的問題是DOM的,我怎麼會選擇用「數據 - 所有的延遲性肌肉痠痛field = name?'

回答

2

使用Attribute selector

[ATTR =值]

表示具有的ATTR的屬性名的元素和其值是準確的 「價值」。

document.querySelectorAll('.detail[data-field="name"]') 
3

您要使用的屬性選擇

// every element with a data-field attribute 
 
var dataFieldElements = document.querySelectorAll('[data-field]'); 
 
console.log(dataFieldElements); 
 

 
// only those elements that have their data-field attribute equal to name 
 
var dataFieldNameElements = document.querySelectorAll('[data-field=name]'); 
 
console.log(dataFieldNameElements);
<div class="person"> 
 
    <div class="detail" data-field="name">Tim</div> 
 
    <div class="detail" data-field="age">24</div> 
 
    <div class="detail" data-field="hair">black</div> 
 
</div> 
 
<div class="person"> 
 
    <div class="detail" data-field="name">Tim</div> 
 
    <div class="detail" data-field="age">34</div> 
 
    <div class="detail" data-field="name">red</div> 
 
</div> 
 
<div class="person"> 
 
    <div class="detail" data-field="name">David</div> 
 
    <div class="detail" data-field="age">56</div> 
 
    <div class="detail" data-field="name">brown</div> 
 
</div>