Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two li with class="tree" in a ul, I want to set a height" to ul.sub-menu when someone clicks on its parent li. But It not working for the second li. Run snippet

document.querySelector(".tree").addEventListener("click",  function () {
    var height = document.querySelector(".sub-menu").scrollHeight;   
    document.querySelector(".sub-menu").style.height = height + "px";
});
.sub-menu {
    position: relative;
    background-color: aqua;
    width: 100px;
    height: 0;
    overflow: hidden;
    transition: height 0.3s;
        
}
<ul>
    <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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...