Categories
JavaScript Answers

How to Use querySelectorAll to Select Elements that Have a Specific Attribute Set?

Spread the love

We can use selectors for selecting elements with specific attributes.

For instance, if we have the following HTML:

<input type='checkbox' value='apple'> apple
<input type='checkbox' value='orange'> orange
<input type='radio' value='grape'> grape

Then we can select all the checkboxes that have a value attribute set by writing:

const inputs = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
console.log(inputs)

input gets all the input elements

[value] narrows down to inputs with the value attribute set.

[type=”checkbox”] means we get the inputs with type attribute set to checkbox .

And :not([value=””] means we get the inputs with value not set to an empty string.

Therefore, inputs should be the checkboxes in the HTML.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *