return elements that match specified CSS selector(s)

Can querySelectorAll() select elements by attribute values?

Answers:

  • Yes, querySelectorAll() can select elements based on their attribute values using attribute selectors. You can use this method to target elements that have specific attributes, attributes with specific values, or attributes that contain certain values.

    Here's how you can use attribute selectors with querySelectorAll():

    1. Select elements with a specific attribute:

      const elementsWithAttr = document.querySelectorAll('[data-custom]');
      

      This selects all elements that have the data-custom attribute, regardless of its value.

    2. Select elements with a specific attribute value:

      const elementsWithAttrValue = document.querySelectorAll('[data-custom="example"]');
      

      This selects all elements that have the data-custom attribute set to "example".

    3. Select elements with an attribute value that starts with a specific string:

      const elementsStartingWith = document.querySelectorAll('[data-custom^="ex"]');
      

      This selects all elements where the data-custom attribute value starts with "ex".

    4. Select elements with an attribute value that ends with a specific string:

      const elementsEndingWith = document.querySelectorAll('[data-custom$="ample"]');
      

      This selects all elements where the data-custom attribute value ends with "ample".

    5. Select elements with an attribute value that contains a specific substring:

      const elementsContaining = document.querySelectorAll('[data-custom*="amp"]');
      

      This selects all elements where the data-custom attribute value contains "amp".

    By using these selectors with querySelectorAll(), you can easily target elements based on their attribute values in your HTML documents.