querySelector will return only the first element.
However it is recommended to delegate from the closest common static container - this is also much more elegant than looping over all elements to add eventListeners to each
document.getElementById("topUl").addEventListener("click", function (e) {
const tgt = e.target.closest("li");
if (tgt.classList.contains("tree")) {
const sm = tgt.querySelector(".sub-menu");
const height = sm.scrollHeight;
sm.style.height = height + "px";
}
});
.sub-menu {
position: relative;
background-color: aqua;
width: 100px;
height: 0;
overflow: hidden;
transition: height 0.3s;
}
<ul id="topUl">
<li class="tree">
<a href="#">Item</a>
<ul class="sub-menu">
<li><a href="#">Sub Item1</a></li>
<li><a href="#">Sub Item1</a></li>
<li><a href="#">Sub Item1</a></li>
</ul>
</li>
<li class="tree">
<a href="#">Item</a>
<ul class="sub-menu">
<li><a href="#">Sub Item2</a></li>
<li><a href="#">Sub Item2</a></li>
<li><a href="#">Sub Item2</a></li>
</ul>
</li>
</ul>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…