3

I know how to select for specific classes using querySelectorAll . But How would I select for DOM object with specific data- attributes.

For example:

 <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>

If I want to select DOMs with a specific class e.g 'detail'

 document.querySelectorAll('.detail')

My question is, How would I select for all doms with 'data-field = name?'

2 Answers 2

7

Use Attribute selector

[attr=value]

Represents an element with an attribute name of attr and whose value is exactly "value".

document.querySelectorAll('.detail[data-field="name"]')
Sign up to request clarification or add additional context in comments.

Comments

4

You want to use the attribute selector

// 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.