rob.m rob.m - 18 days ago 5
Javascript Question

How to add class to parent in javascript?

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 js 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:


  • 1500 is single and doesn't have a child

  • 1400 has a child 1401



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>

Answer

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");