0

I need to see if an element is in another list or not but they are not in order and they are not equal size.

let list1 = [10 , 4 , 5]
let list 2 = [4 , 5]

I tried this but this only works if they are in same order.

  for(var i=0;i<=document.querySelectorAll('.datename').length;i++){

    if(document.querySelectorAll('.inputname')[i].value==document.querySelectorAll('.datename')[i].innerHTML){
        console.log(document.querySelectorAll('.other')[c].classList)
           document.querySelectorAll('.other')[c].classList.add('active2')
    }
}
Cid
  • 14,968
  • 4
  • 30
  • 45
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – Andrew Parks Mar 09 '23 at 16:18
  • What do these DOM elements look like? In particular, what `type` are the `input` elements, and does their `value` actually change? (For instance, `type="checkbox"` and `type="radio"` inputs generally have stable `value` values, but not usually the others...) – T.J. Crowder Mar 09 '23 at 16:20
  • Side note: `querySelectorAll` returns a new `NodeList` every time you call it, probably best to do your queries once just before the loop(s), remember the lists to variables, and reuse those lists rather than asking the browser to go find the elements again on every loop iteration. – T.J. Crowder Mar 09 '23 at 16:21

2 Answers2

0

You can put all the element values into an array first, then use Array#includes to check for a match.

let vals = Array.from(document.querySelectorAll('.inputname'), el => el.value);
for (const el of document.querySelectorAll('.datename')) {
    if (vals.includes(el.textContent)) {
        // do something
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

The possible solution you have tried is:

const input = document.querySelectorAll('.input');
const data = document.querySelectorAll('.data');

for (let i = 0; i < input.length; i++) {
  const inputValue = input[i].value;
  
  if (Array.from(data).some(dateElement => dateElement.innerHTML === inputValue)) {
    console.log('Element ' + inputValue + ' is included in datename list.');
    // do something if the element is included, e.g.
    document.querySelectorAll('.other')[i].classList.add('active2');
  } else {
    console.log('Element ' + inputValue + ' is not included in datename list.');
  }
}

Or,

If you want to check if data of an array contains in another array and if they are not same length then you can use the include() method.

let list1 = [10, 4, 5];
let list2 = [4, 5];

for (let i = 0; i < list2.length; i++) {
  if (list1.includes(list2[i])) {
    console.log("Element " + list2[i] + " is in list1.");
  }
}

the output will be:

//Element 4 is in list1.

//Element 5 is in list1.

check the sandbox: https://codesandbox.io/embed/sleepy-stitch-jb3c6l?fontsize=14&hidenavigation=1&theme=dark

Nafiz Ahmed
  • 23
  • 1
  • 6