10

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:

  • 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>
tonys
  • 3,855
  • 33
  • 39
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • you would be looking for `btn.parentNode` instead of `btn.parent()` if I am reading your code right. – Jhecht Nov 19 '16 at 22:19

3 Answers3

29

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");
Ram
  • 143,282
  • 16
  • 168
  • 197
6

Also consider parentElement as an alternative to parentNode:

btn.parentElement.classList.add("active");
Bardy
  • 2,100
  • 1
  • 13
  • 11
1

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");
});
Sreekanth
  • 3,110
  • 10
  • 22