querySelectorAll() the best JavaScript function in the world!

Can querySelectorAll() select elements based on their attributes or data values?

1 answer

  1. Yes, `querySelectorAll()` can select elements based on their attributes or data values. To do so, you can use attribute selectors in your query. Here are some examples:

    1. Select all elements with a specific attribute:

    ```javascript
    document.querySelectorAll('[data-custom]');
    ```

    2. Select all elements with a specific attribute value:

    ```javascript
    document.querySelectorAll('[data-custom="value"]');
    ```

    3. Select all elements with an attribute value containing a specific word:

    ```javascript
    document.querySelectorAll('[data-custom~="value"]');
    ```

    4. Select all elements with an attribute value starting with a specific string:

    ```javascript
    document.querySelectorAll('[data-custom^="value"]');
    ```

    5. Select all elements with an attribute value ending with a specific string:

    ```javascript
    document.querySelectorAll('[data-custom$="value"]');
    ```

    6. Select all elements with an attribute value containing a specific substring:

    ```javascript
    document.querySelectorAll('[data-custom*="value"]');
    ```

Related Questions