代码之家  ›  专栏  ›  技术社区  ›  Jeff Higgins

使用Javascript选择DOM元素

  •  0
  • Jeff Higgins  · 技术社区  · 2 年前

    我有以下HTML和Javascript的片段。

    在Javascript中,我引用了一个按钮元素 我想从中获得对第一个元素的引用 类“定理”的封闭div元素中的类“证明”的。

    到目前为止,我在Javascript片段中显示的最佳尝试没有成功。

    任何帮助都将不胜感激。

    <section>   
       <div id="t1" class="theorem">
    
            <div>
                <span>Theorem   1:</span>
                <button class="toggle">Proof</button>
            </div>  
    
            <p>
                Text of my Theorem 1.
            </p>
    
            <div class="proof">
                Proof of my Theorem 1.
            </div>  
            
        </div>
    </section>
    
    <script>
        var buttons = document.getElementsByClassName("toggle");
        var i;
        for (i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener("click", function() {
                var theorem = this.closest("theorem");                  
                var proof = parent.querySelector(".proof");
            });
        }
    </script>
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   Alexander Nenashev    2 年前

    你忘了两件事:

    1. 使用 . 之前 theorem 正确选择父项
    2. 使用 定理 变量来找到证明elem。

    <section>   
       <div id="t1" class="theorem">
    
            <div>
                <span>Theorem   1:</span>
                <button class="toggle">Proof</button>
            </div>  
    
            <p>
                Text of my Theorem 1.
            </p>
    
            <div class="proof">
                Proof of my Theorem 1.
            </div>  
            
        </div>
    </section>
    
    <script>
        var buttons = document.getElementsByClassName("toggle");
        var i;
        for (i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener("click", function() {
                var theorem = this.closest(".theorem");                  
                var proof = theorem.querySelector(".proof");
                console.log(proof);
            });
        }
    </script>
        2
  •  -1
  •   Fernando A. León    2 年前

    最好选择元素 document.querySelector() 用于单个元素或 document.querySelectorAll() 对于多个元素

    有两个选项可以使用CSS选择器来获取元素