如何解决如何按类获取数组中的多个元素?
我正在尝试使用数组获取多个元素。我不擅长描述,所以我会尝试展示。
var modal = document.querySelectorAll(".myModal")[0]; // <-- gets the first element in an array
var modal = document.querySelectorAll(".myModal")[1]; // <-- gets the second element in an array; doesn't work
感谢任何帮助。谢谢。
解决方法
你可以这样试试:
var modal = document.querySelectorAll(".myModal"); //one time
modal[0] //first element
modal[1] //second element
,
var parent = document.querySelectorAll('.myModal');
Array.prototype.slice.call(parent).forEach(function(child){
// your code
});
希望您正在寻找这个,因为您的问题并没有让您知道您到底想要什么。
,您可以通过多种方式执行此操作,您可以在 Accessing the matches
阅读有关如何遍历它的更多信息请注意,您不能两次使用相同的变量,在您的代码中重命名第二个变量即可:Declaring two variable with the same name
// one way
let modal0 = document.querySelectorAll(".myModal")[0];
let modal1 = document.querySelectorAll(".myModal")[1];
console.log("one way")
console.log(modal0)
console.log(modal1)
//another way
const modalElemenet = document.querySelectorAll(".myModal");
let firstElement = modalElemenet[0];
let secondElement = modalElemenet[1];
console.log("second way")
console.log(firstElement);
console.log(secondElement);
// take all childrens
const modal = document.querySelectorAll(".myModal");
console.log("take all")
modal.forEach(e => console.log(e));
<div class="myModal"> 1 </div>
<div class="myModal"> 2 </div>
<div class="myModal"> 3 </div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。