我知道如何使用querySelectorAll选择特定的类。但是我如何选择具有特定数据属性的DOM对象。
例如:
<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>
如果我想选择具有特定类别的DOM,例如“detail”
document.querySelectorAll('.detail')
我的问题是,如何使用'data-field = name?'
为所有doms选择答案 0 :(得分:4)
您想使用属性选择器
// 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>
答案 1 :(得分:3)
[ATTR =值]
表示属性名称为attr且其值正好为&#34; value&#34;的元素。
document.querySelectorAll('.detail[data-field="name"]')