为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 querySelectorAll 选择所有 DIV?

如何使用 querySelectorAll 选择所有 DIV?

慕工程0101907 2023-10-20 10:26:16
我想调用 all divs 因为TUTTIiDIV它已经是一个数组。当我运行此代码时,控制台看起来不错,但代码无法按预期工作。如何选择数组的所有元素TUTTIiDIV?document.addEventListener("DOMContentLoaded", function() {  var TUTTIiDIV = document.querySelectorAll("div");  document TUTTIiDIV.onclick = function() {    coloraicontorni()  }}); //END DOMcontentLoadedfunction 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>
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

使用最近容器中的委托来选择单击该容器中的任何内容


window.addEventListener("load", function() { // when the page has loaded

  document.getElementById("container").addEventListener("click", function(e) {

    [...this.querySelectorAll("div")] // the "this" is the container

    .forEach(div => div.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="container">

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

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

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

</div>

如果您只想单击 div,请执行以下操作


window.addEventListener("load", function() { // when the page has loaded

  document.getElementById("container").addEventListener("click", function(e) {

    if (e.target.tagName === "DIV") { // only if we click a div in the container

      [...this.querySelectorAll("div")] // the "this" is the container

      .forEach(div => div.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="container">

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

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

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

</div>


查看完整回答
反对 回复 2023-10-20
  • 1 回答
  • 0 关注
  • 60 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信