I have the following piece of JS / prototypeJS, that I would like to write in full vanilla JS. I wish to click on an element (one out of a number of elements with the same class - faq-container
) and add a specific class (in this case faq-display
) and add this class only to the parent container (faq-block
).
I understand that the pure JS function is something to do with .parent.addClass
but can not find a relevant example to my situation.
The prototypeJs lines are:
faqContainers[i].addEventListener('click', function(e) {
and
var faqToggle = e.target.up('.faq-block');
The script file is:
var faqContainers = document.getElementsByClassName('faq-container');
for (var i = 0; i < faqContainers.length; i++) {
faqContainers[i].addEventListener('click', function(e) {
var faqToggle = e.target.up('.faq-block');
if (faqToggle.classList.contains('faq-display')) {
faqToggle.classList.remove('faq-display');
} else {
faqToggle.classList.add('faq-display');
}
});
}
Many thanks indeed!
Here's an example substituting closest() for PrototypeJS up():