How do I get the last element child for every item

2019-08-17 09:24发布

问题:

So currently with this code with an onclick I am able to open the sub-menu items.

The issue is when I click on one of the items to drop down the menu they all open, but I only want the ones I click on to open not all of them.

function myDropdown() {
var arr = Array.from(document.getElementsByClassName('sub-menu-wrap'));
for (let el of arr) {
    var x = el.lastElementChild;
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
}

If you go here https://staging.information-age.com/ and look at the third menu with the icon on the right, this is the menu I am working on so you can get a better understanding of what I mean.

And to add this menu is being generated dynamically by Wordpress using the wp_nav_menu function.

Hope someone can help!

回答1:

So your problem is, imo, that you probably shouldn't be deciding the click function in the html like that.

It looks to me like the site already has jQuery installed on it, so why don't you use that to make things simpler? You want to assign a click to the <i> elements like this:

$('#ib-menu i').click(function() { /* do your work in here*/ });

Inside the function, this is the currently clicked element, and $(this) is the jQuery-selected version of that element. You can use jQuery to add and remove classes, and add and remove styles, and find elements that are the parent or children of the element you've selected.

For example, if you want to find the 'sub-menu-wrap' that is the parent of the currently selected element, inside the function you would write var subMenu = $(this).closest('.sub-menu-wrap') and then, from there, you can check and modify styles and classes

jQuery will make your life loads easier. Every question you have will have a million answers across the internet already as well.



回答2:

The onclick handler should be something along the lines of

let all = Array.from(document.getElementsByClassName('sub-menu-wrap'));

// current or "this" if you use onclick, 2 is the offset of the clicked menu item, just for testing
let current = all[2]; // change all[2] to this

for (let el of all) {
  el.querySelector(".sub-menu").style.display = (el === current ? "block" : "none");
}