[英]How do I get the last element child for every item in an array
So what I need to do is grab the last element child for every item in an array. 所以我需要做的是抓住数组中每个项目的最后一个元素子元素。
function myDropdown() {
var x = document.getElementsByClassName('sub-menu-wrap')[0].lastElementChild
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
I know that this works: 我知道这有效:
document.getElementsByClassName('sub-menu-wrap')[0].lastElementChild
But instead of defining which item in the array I want it to use I need it to just dynamically grab every item in the array and get the .lastElementChild
for them. 但是我没有定义数组中我希望它使用哪个项目,而是需要它来动态获取数组中的每个项目并为它们获取
.lastElementChild
。
Just to add this I need this function to work as onclick and only get applied to any of the items when they are clicked on 只是为了添加这个,我需要这个函数作为onclick工作,只有在点击它们时才会应用于任何项目
Hope someone can help! 希望有人可以帮忙!
var arr = Array.from(document.getElementsByClassName('sub-menu-wrap'));
for (let el of arr) {
var x = el.lastElementChild;
/// do what you want to x here
}
Actually I don't think you need to convert it to an array with Array.from if you're doing for..of..
, but you would if you're doing arr.forEach()
实际上我认为你不需要将它转换为带有Array.from的数组,如果你正在做
for..of..
,但如果你正在做arr.forEach()
你会
Try like this. 试试这样吧。 get the array of the class
sub-menu-wrap
and loop it and hide/show your last child element 获取类
sub-menu-wrap
的数组并将其循环并隐藏/显示您的最后一个子元素
function myDropdown() { var array = Array.from(document.getElementsByClassName('sub-menu-wrap')); for (let data of array) { var x = data.lastElementChild; if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } } myDropdown()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sub-menu-wrap"> <div>hi1</div> <div>hi2</div> <div>hi3</div> </div> <div class="sub-menu-wrap"> <div>hi1</div> <div>hi2</div> <div style="display:none">hi3</div> </div>
If you want to hide the clicked elements last child 如果要隐藏最后一个孩子的被点击元素
function hideLast(e) { var x = e.lastElementChild; if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sub-menu-wrap" onclick="hideLast(this)"> <div>hi1</div> <div>hi2</div> <div>hi3</div> </div> <div class="sub-menu-wrap" onclick="hideLast(this)"> <div>hi1</div> <div>hi2</div> <div style="display:none">hi3</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.