Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class to parent in javascript?

Tags:

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 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>
like image 982
rob.m Avatar asked Nov 19 '16 22:11

rob.m


Video Answer


3 Answers

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");
like image 164
undefined Avatar answered Oct 17 '22 05:10

undefined


Also consider parentElement as an alternative to parentNode:

btn.parentElement.classList.add("active");
like image 36
Bardy Avatar answered Oct 17 '22 04:10

Bardy


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");
});
like image 1
Sreekanth Avatar answered Oct 17 '22 04:10

Sreekanth