var toggleButton = document.getElementsByClassName('toggle-button')
for (var i = 0; i < toggleButton.length; i++) {
toggleButton[i].addEventListener('click', function () {
toggleButton[i].parentElement.parentElement.children[2].style.background = "red";
});
}
<div>
<div>
<button class="toggle-button">view</button>
</div>
<div>content</div>
<div>the div which I want to apply changes on</div>
</div>
What's wrong with this code? When I run it it gives me this error "Uncaught TypeError: Cannot read property 'parentElement' of undefined at HTMLButtonElement."
*I don't want to apply the CSS changes on a class I need it to be applied on this specific div using DOM.
styleattribute, and more broadly: if you want to do something on the JS side, use the JS APIs for that thing, rather than trying to change the "markup" for DOM elements. In this case, add/toggle/remove CSS classes instead, using the element.classList namespace, so:toggleButtons.forEach(e => e.addEventListener("click", _event => e.classList.toggle("active")))with a CSS class.active { background-color: red; }.iin click handler: after loop it will be1(or equal to togleButton.length), and there is no toggleButton[1]. Usingthiswould make more sense here.Array.from(...)to get.forEach, which solves the problem of anibeing the wrong value.