That block appears with a class that is passed through input.

The problem is that when you erase a number, the Uncaught TypeError: Cannot read property 'classList' of undefined error appears in the console.

I do not understand why, I wrote the condition, if there is no such element in the array, then nothing needs to be done

<style> .hidden { display: none; } .img { width: 200px; height: 200px; } .img1 {background: green;} .img2 {background: blue;} .img3 {background: red;} </style> <input type="text" class="input"> <div class="img img1 hidden"></div> <div class="img img2 hidden"></div> <div class="img img3 hidden"></div> <script> var input = document.querySelector('.input'); var img = document.querySelectorAll('.img'); var arr = []; img.forEach(function(el, i) { arr.push(i); }) input.oninput = function() { img.forEach(function(element, i) { if(arr.indexOf(Number(input.value)) != -1) { img[input.value - 1].classList.remove('hidden'); } else{ img[i].classList.add('hidden'); } }) } </script> 

    1 answer 1

    You have this condition

     if(arr.indexOf(Number(input.value)) != -1) { img[input.value - 1].classList.remove('hidden'); } 

    If input.value = '' the string Number (input.value) returns 0, and then you get img [input.value - 1], which is equal to img [-1], respectively, there is no such element in the array. Redo the check.

     input.oninput = function() { img.forEach(function(element, i) { if(arr.indexOf(Number(input.value)-1) != -1) { img[Number(input.value - 1)].classList.remove('hidden'); } else{ img[i].classList.add('hidden'); } }) } 
    • if you write img [input.value], then there will also be an error - DivMan
    • I already insert it directly, I still get an error - DivMan
    • one
      if (input.value == '') {img [0] .classList.add ('hidden'); } if (arr.indexOf (Number (input.value))! = -1) {img [Number (input.value)]. classList.remove ('hidden'); } - GlWhitefoot
    • img [input.value] in case an empty value will look for an element with the key '', and not 0 - GlWhitefoot