如何使用 querySelectorAll 选择所有 DIV?

我想调用 all divs 因为TUTTIiDIV它已经是一个数组。当我运行此代码时,控制台看起来不错,但代码无法按预期工作。

如何选择数组的所有元素TUTTIiDIV

document.addEventListener("DOMContentLoaded", function() {

  var TUTTIiDIV = document.querySelectorAll("div");

  document TUTTIiDIV.onclick = function() {

    coloraicontorni()

  }


}); //END DOMcontentLoaded


function coloraicontorni() {

  var TUTTIiDIV = document.querySelectorAll("div");

  for (i = 0; i <= TUTTIiDIV.length; i++) {

    TUTTIiDIV[i].classList.add('contorno');

  }

};

* {

  box-sizing: border-box;

}


body {

  background-color: antiquewhite;

}


#rosso {

  width: 25%;

  height: 150px;

  background-color: red;

  display: inline-block;

}


#blu {

  width: 25%;

  height: 150px;

  background-color: blue;

  display: inline-block;

}


#giallo {

  width: 25%;

  height: 150px;

  background-color: yellow;

  display: inline-block;

}


.contorno {

  border: 8px solid black;

}

<div id="rosso"></div>

<div id="blu"></div>

<div id="giallo"></div>


慕工程0101907
浏览 94回答 1
1回答

慕尼黑8549860

使用最近容器中的委托来选择单击该容器中的任何内容window.addEventListener("load", function() { // when the page has loaded&nbsp; document.getElementById("container").addEventListener("click", function(e) {&nbsp; &nbsp; [...this.querySelectorAll("div")] // the "this" is the container&nbsp; &nbsp; .forEach(div => div.classList.add('contorno'));&nbsp; });});* {&nbsp; box-sizing: border-box;}body {&nbsp; background-color: antiquewhite;}#rosso {&nbsp; width: 25%;&nbsp; height: 150px;&nbsp; background-color: red;&nbsp; display: inline-block;}#blu {&nbsp; width: 25%;&nbsp; height: 150px;&nbsp; background-color: blue;&nbsp; display: inline-block;}#giallo {&nbsp; width: 25%;&nbsp; height: 150px;&nbsp; background-color: yellow;&nbsp; display: inline-block;}.contorno {&nbsp; border: 8px solid black;}<div id="container">&nbsp; <div id="rosso"></div>&nbsp; <div id="blu"></div>&nbsp; <div id="giallo"></div></div>如果您只想单击 div,请执行以下操作window.addEventListener("load", function() { // when the page has loaded&nbsp; document.getElementById("container").addEventListener("click", function(e) {&nbsp; &nbsp; if (e.target.tagName === "DIV") { // only if we click a div in the container&nbsp; &nbsp; &nbsp; [...this.querySelectorAll("div")] // the "this" is the container&nbsp; &nbsp; &nbsp; .forEach(div => div.classList.add('contorno'));&nbsp; &nbsp; }&nbsp; });});* {&nbsp; box-sizing: border-box;}body {&nbsp; background-color: antiquewhite;}#rosso {&nbsp; width: 25%;&nbsp; height: 150px;&nbsp; background-color: red;&nbsp; display: inline-block;}#blu {&nbsp; width: 25%;&nbsp; height: 150px;&nbsp; background-color: blue;&nbsp; display: inline-block;}#giallo {&nbsp; width: 25%;&nbsp; height: 150px;&nbsp; background-color: yellow;&nbsp; display: inline-block;}.contorno {&nbsp; border: 8px solid black;}<div id="container">&nbsp; <div id="rosso"></div>&nbsp; <div id="blu"></div>&nbsp; <div id="giallo"></div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript