Categories
JavaScript Answers

How to use querySelectorAll only for elements that have a specific attribute set with JavaScript?

Spread the love

Sometimes, we want to use querySelectorAll only for elements that have a specific attribute set with JavaScript.

In this article, we’ll look at how to use querySelectorAll only for elements that have a specific attribute set with JavaScript.

How to use querySelectorAll only for elements that have a specific attribute set with JavaScript?

To use querySelectorAll only for elements that have a specific attribute set with JavaScript, we call querySelectorAll with a selector that matches the attribute name and value we’re looking for.

For instance, we write

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

to call querySelectorAll with the value attribute of checkbox inputs that has value not equal to an empty string.

This will return a node list of all checkboxes that has value attribute not set to an empty string.

Conclusion

To use querySelectorAll only for elements that have a specific attribute set with JavaScript, we call querySelectorAll with a selector that matches the attribute name and value we’re looking for.

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 *