skip to Main Content

I have the following snippets of HTML and Javascript.

In the Javascript I have a reference to a button element
from which I want to get a reference to the first element
of class "proof" in the enclosing div element of class "theorem".

My best attempt so far shown in the Javascript snippet dosen’t work.

Any help will be much appreciated.

<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

Answers


  1. it’s better select elements with document.querySelector() forsingle element or document.querySelectorAll() for multiple elements

    two options can use CSS selectors for getting elements

    Login or Signup to reply.
  2. You forgot 2 things:

    1. use . before theorem to properly select the parent
    2. use theorem variable to find the proof 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search