Create a drop-down multi-level menu.
The problem is that the function does not work on those elements that come after an element that does not satisfy the if condition.
The code above is a simplified analogue of the functional: by clicking it is necessary to color what is clicked, provided that there is one more element next to it. Question: how to make the function work with all elements that have a "neighbor".
window.onload = function(e) { var sublist = document.querySelectorAll('.dropdown-list li a'); for (var i=0; i<sublist.length; i++) { if (sublist[i].nextSibling.length !== null) { sublist[i].onclick = function(event) { // event.preventDefault(); this.style.background = 'red'; } } } } <div class="dropdown-list"> <li><a href="#">111</a><span>000</span></li> <li><a href="#">222</a><span>000</span></li> <li><a href="#">333</a><span>000</span></li> <li><a href="#">444</a></li> <li><a href="#">555</a><span>000</span></li> <li><a href="#">666</a></li> <li><a href="#">777</a><span>000</span></li> </div>
sublist[i].nextSiblingreturns the next ancestor, and this is the DOM object of the model, it does not have the.lengthproperty.lengthit is alwaysundefinedor theCannot read property 'length' of null(…)errorCannot read property 'length' of null(…)if there is no ancestor at all - Vasily Barbashev.nextSibling.length !== nullchecking if there’s something else next to the elements via.nextSibling.length !== null. How then is it better to implement a submenu display? - lexxla, but byli-.dropdown-list li, then you can find out how many children there will be inliwith the help ofchildElementCount. And you will know that 1 is only a link, and 2 is a link and aspan, your second level. That is if I understand you correctly) - Vasily Barbashev