Search code examples
javascriptqueryselector

querySelector select attributes that starts with "data-"


This is a simple doubt, I have in my HTML many attributes that starts with data-:

<span data-something="some"></span>
<p data-some="some"></p>
<div data-a-thing="some"></div>
<a data-other-thing="some"></a>
<section data-some-attribute="some"></section>
<span data-asd="some"></span>
<p  data-some-invented-attribute="some"></p>

I want to select all tags whose attributes starts with: data-*, I want to use RegExp but isn't possible, is there any way to do it? Thanks!


Solution

  • I don't think there's any way to select dynamic attributes with a single selector. But you could select all elements and filter those by attributes that have one that starts with data:

    console.log(
      [...document.querySelectorAll('*')]
        .filter(elm => [...elm.attributes].some(
          attrib => attrib.name.startsWith('data')
        ))
    );
    <span>don't select me</span>
    <span data-something="some"></span>
    <p data-some="some"></p>
    <div data-a-thing="some"></div>
    <a data-other-thing="some"></a>
    <section data-some-attribute="some"></section>
    <span data-asd="some"></span>
    <p data-some-invented-attribute="some"></p>

    Another method, using dataset:

    console.log(
      [...document.querySelectorAll('*')]
        .filter(elm => Object.keys(elm.dataset).length)
    );
    <span>don't select me</span>
    <span data-something="some"></span>
    <p data-some="some"></p>
    <div data-a-thing="some"></div>
    <a data-other-thing="some"></a>
    <section data-some-attribute="some"></section>
    <span data-asd="some"></span>
    <p data-some-invented-attribute="some"></p>