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
it’s better select elements with
document.querySelector()
forsingle element ordocument.querySelectorAll()
for multiple elementstwo options can use CSS selectors for getting elements
You forgot 2 things:
.
beforetheorem
to properly select the parenttheorem
variable to find the proof elem.