最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLImageElement.<anonymou

programmeradmin1浏览0评论

Here is the code:

let imagenes = document.querySelectorAll(".team");
let modal = document.querySelectorAll("#modal");
let img = document.querySelectorAll("#modal__img");
let boton = document.querySelectorAll("#modal__boton");

for (let i = 0; i < imagenes.length; i++){
  imagenes[i].addEventListener("click", function(e){
    modal.classList.togle("modal--open");
  })
}

Error:

Uncaught TypeError: Cannot read property 'toggle' of undefined    at HTMLImageElement.<anonymous>"

Here is the code:

let imagenes = document.querySelectorAll(".team");
let modal = document.querySelectorAll("#modal");
let img = document.querySelectorAll("#modal__img");
let boton = document.querySelectorAll("#modal__boton");

for (let i = 0; i < imagenes.length; i++){
  imagenes[i].addEventListener("click", function(e){
    modal.classList.togle("modal--open");
  })
}

Error:

Uncaught TypeError: Cannot read property 'toggle' of undefined    at HTMLImageElement.<anonymous>"
Share Improve this question edited Dec 8, 2021 at 1:28 SuperStormer 5,4275 gold badges28 silver badges39 bronze badges asked Aug 6, 2020 at 5:28 Maria Fernanda VillavicencioMaria Fernanda Villavicencio 111 gold badge1 silver badge2 bronze badges 1
  • I suspect this snippet code doesn't reflect correctly with the error since togle is different from toggle. So please make sure you copy & paste the accurate snippet from your code. – tmhao2005 Commented Aug 6, 2020 at 6:04
Add a ment  | 

2 Answers 2

Reset to default 2

If you are using a querySelectorAll, you will get an HTML collection, therefore you will need to iterate through it's elements to toggle a class. It's faster to target by if you want to toggle only one element, but if you need to toggle more than one, your code would look something like this

const elements = document.quesySelectorAll('.myClass');
elements.forEach(x => x.classList.toggle('otherClass');

document.querySelectorAll returns a NodeList with array-like data structure. Hence, modal is an array with no classList property. Use document.getElementById; it's faster anyways:

let modal = document.getElementById("#modal");

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论