简体   繁体   中英

How to select nested UL element without class in JavaScript

In my Joomla template I've created a vertical menu including a dropdown which should "push" the elements below away when opening a submenu onclick. Somehow I don't get it to work..

I am trying to grab the UL inside an LI, but how can I do this in JavaScript without the UL's having a class or ID.

I've come to this yet:

function getElements(){
var listitems = {};
for(var i = 0; i< arguments.length; i++){
    var id = arguments[i];
    var item = navigation.getElementsByTagName("li");
    if (item == null)
        throw new Error ("No list items found.");
    listitems[id] = item;
}
return listitems;
}

Now I should get something like: (I now the following code is impossible, but it describes what I am trying)

var nav = document.getElementById("navigation");
var nestedList = nav ul li ul;
nestedList.onclick(nav ul li ul.style = "display: block";);

The HTML looks like:

<div id="navigation">
<ul>
<li class="parent">
    <ul><li></li></ul>
</li>
</ul>
</div>

The CSS looks like:

#navigation ul li ul{display: none;}

Now I want it to display: block when clicking on .parent

Thanks!

Since you already have MooTools included in your page, something like this should work (not a MooTools expert here):

$('#navigation li.parent').addEvent('click', function () {
  $('#navigation li.parent ul li ul').setStyle('display', 'block');
});


Old post:

Pure JS (this is not the full code, you have to loop over the elements several times for adding the click listener and applying the styles):

 var listItems = document.querySelectorAll("nav ul li ul"); var count = listItems.length; for (var i=0; i<count; i++) { var item = listItems.get(i); item.style.display = "block"; } 

Of course the easiest is using jQuery or some other library. To do it with pure JavaScript for modern browsers, use JS querySelector . Otherwise you will spend a lot of time in this.

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