return elements that match specified CSS selector(s)

Can querySelectorAll() be used to select elements by attribute?

Answers:

  • Yes, querySelectorAll() can be used to select elements by attribute in JavaScript. You can specify attributes in your selector string using the attribute selector syntax.

    Here are some examples:

    1. Selecting elements with a specific attribute:

      // Select all elements with the 'data-example' attribute
      const elements = document.querySelectorAll('[data-example]');
      
    2. Selecting elements with a specific attribute and value:

      // Select all elements where 'role' attribute equals 'button'
      const buttons = document.querySelectorAll('[role="button"]');
      
    3. Selecting elements with an attribute that starts with a specific value:

      // Select all elements where 'data-' attribute starts with 'data-'
      const dataElements = document.querySelectorAll('[data-*]'); // Note: this will not work with wildcards in CSS selectors, you can use ^ for starts with
      
    4. Selecting elements with an attribute that contains a specific substring:

      // Select elements where 'class' attribute contains 'active'
      const activeElements = document.querySelectorAll('[class*="active"]');
      
    5. Combining attribute selectors with other selectors:

      // Select all <input> elements with 'type' attribute equals 'text'
      const textInputs = document.querySelectorAll('input[type="text"]');
      

    In summary, querySelectorAll() is a powerful method that allows you to select elements based on a variety of criteria, including attributes.

Related Questions: