简体   繁体   中英

How do I get the last element child for every item in an array and then show them if they are clicked on

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!

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");
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM