skip to Main Content

Given HTML:

<div class="element" data-name="cat">
<div class="element" data-name="bird">
<div class="element" data-name="dog">

I want to find only the elements that match a data attribute that im keeping in an array like this

let Array1 = ["dog","cat","lizard"]

I thought I could do it with querySelectorAll and data attribute filter but its not working at all. Returns an empty nodelist.

let Elements = document.body.querySelectorAll('.element[data-name="${Array1}"]')

Im working on a firefox extension looking at a webpage, so I can’t touch the HTML and would prefer to stay in pure javascript. Im very new at programming and this is a personal project.

2

Answers


  1. Unfortunately, there’s no shortcut. I would recommend to loop through your array of possible values. Since querySelectorAll returns a NodeList, you need to use spread syntax (...) to expand it into your array of captured elements.

    const className = 'element',
        attribute = 'data-name',
        attribute_values = ['cat', 'bird', 'dog'],
        elements = [];
    for (let value of attribute_values) {
        elements.push(...document.querySelectorAll('.' + className + '[' + attribute + '=' + value + ']'));
    }
    
    Login or Signup to reply.
  2. Explanation

    There is no direct way to do that, because the querySelector is designed to only select elements based on a single css/attribute selector. However, we can achieve that by repeating the query for multiple times.

    Code

    // Method 1: Loop through all the elements with attributes ['data-name']
    // Then, apply filter to search for particular attribute value
    const elementsWithAttrDataName = document.querySelectorAll('[data-name]');
    const results = Array.from(elementsWithAttrDataName).filter(ele => {
      return ele.getAttribute('data-name') === 'cat' || ele.getAttribute('data-name') === 'dog';
    });
    console.log(results.length);
    
    
    // Method 2: Loop through all the keys you want to search for
    var elements = [];
    let keys = ["cat", "dog"];
    keys.forEach(function(key){
        elements.push(document.querySelectorAll('[data-name="'+key+'"]'));
    });
    
    console.log(elements.length);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search