Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - How to add event listener with same class?

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>

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

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...