Search code examples
arraysqueryselector

Select DOM elements by data attribute using array of integers?


If I have this: [ 2, 5, 6, 8, 9 ].

And I need to select all table rows with a data attribute like "data-id=n" that has a value contained in the array.

What would be the most efficient way?

Imagine: let rows = document.querySelector("#table tr data-id=[ 2, 5, 6, 8, 9 ]") ... man, wouldn't that be lovely?

I just slammed this together:

...
        for ( const key in flags ) {
            let arr = flags[ key ].records;

            arr.forEach( id => {
                let row = autotable.querySelector('.autotable-row[data-id="' + id + '"] td.' + key);

                if ( row ) {
                    row.classList.add(flags[ key ].flag);
                }
            });
        }
...

Solution

  • You can map the array to create your selector:

    const rows = document.querySelectorAll([2, 5, 6, 8, 9].map(id => `tr[data-id="${id}"]`).join(','));
    
    console.log([...rows]);
    <table id="table">
      <tr data-id="1"></tr>
      <tr data-id="2"></tr>
      <tr data-id="3"></tr>
      <tr data-id="4"></tr>
      <tr data-id="5"></tr>
      <tr data-id="6"></tr>
      <tr data-id="7"></tr>
      <tr data-id="8"></tr>
      <tr data-id="9"></tr>
    </table>