How to find a group of elements by dataset?

  • 0
    Hello!
    I have a lot of elements on the page with a data-value attribute.
    For example: data-value = "11" or data-value = "171";
    There is also an array: data_codes = [11, 16, 129, ...].
    Could you please tell me if there is a more efficient (fast) way to get elements (whose data-value is equal to one of the array elements) than iterating over data_codes and calling for each element:
    document.querySelector("[data-value = " +data_codes[i]+"]")
    JavaScript Anonymous, Jul 12, 2020

  • 2 Answers
  • 0
    document.querySelectorAll(`[data-value = "11"], [data-value = "171"], ...`)


    You can also limit your search to a specific part of the page.

    const container = document.body.querySelector('#conteiner')
    container.querySelectorAll(`[data-value = "11"], [data-value = "171"], ...`)
    Anonymous

  • 0
    Please tell me if there is a more efficient (fast) way to get elements (whose data-value is equal to one of the array elements) than iterating over data_codes and calling for each element:
    More efficient - I'm not sure. There is just another way:

    let data_codes = [ 11, 16, 129];
    let dataArr = data_codes.map(v=>`[data-value="${v}"]`);

    document.querySelectorAll(dataArr).forEach(v=>{
    console.log(v.dataset.value)
    });
    Joshua Cannon

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!