Not jQuery as I would simply do $("this").parent().addClass("active");
but in pure javascript. This is because i don't want to mix up Javascript and jQuery on the following code:
var clickedPath = this.getElement();
clickedPath.classList.add("active");
var classes = clickedPath.getAttribute('class').match(/\d+/g) || [];
buttons.forEach(function(btn) {
var method = classes.indexOf(btn.getAttribute('data-date')) > -1 ? 'add' : 'remove';
btn.classList[method]('active');
//btn.parent().addClass("active");
});
UPDATE
This is the HTML starting case before the classes are added:
<ul>
<li>1500</li>
<li>1400
<ul>
<li>1401</li>
</ul>
</li>
</ul>
We have 2 situations:
If I am adding the class active
to 1500, it's fine and I can use the code provided in the answer:
btn.parentNode.classList[method]('active');
But If I add the class to 1401, also 1400 should have it, so the followings are the two cases:
<ul>
<li class="active">1500</li>
<li>1400
<ul>
<li>1401</li>
</ul>
</li>
</ul>
Or
<ul>
<li>1500</li>
<li class="active">1400
<ul>
<li class="active">1401</li>
</ul>
</li>
</ul>
You mention " i don't want to mix up js and jQuery on the following code" but you are actually mixing vanilla DOM APIs with jQuery methods. .parent
and .addClass
are jQuery functions. You can code:
btn.parentNode.classList.add("active");
Also consider parentElement
as an alternative to parentNode
:
btn.parentElement.classList.add("active");
You need .parentNode on the element.
Something like this.
var clickedPath = this.getElement();
clickedPath.classList.add("active");
var classes = clickedPath.getAttribute('class').match(/\d+/g) || [];
buttons.forEach(function(btn) {
var method = classes.indexOf(btn.getAttribute('data-date')) > -1 ? 'add' : 'remove';
btn.classList[method]('active');
btn.parentNode.classList.add("active");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With