javascriptparent-node

How to examine parentNode classList in an if else statement in javascript


I have a function which is called whenever a checkbox is clicked from a particular group. I am trying to add a class to the input's parent wrapper when the checkbox is checked, and then remove the class when it isn't checked. My problem is, I can't seem to get parentNode and classList working together.

eg. This code works:

$(this.parentNode).css( "border", "3px solid red" );

But this code returns an undefined error

alert($(this.parentNode).classList

For context, here's what I'm eventually trying to get to:

    if ($(this.parentNode.parentNode).find('.form-type-checkbox').classList.contains("chkbox-checked")) {
      $(this.parentNode.parentNode).find('.form-type-checkbox').removeClass("chkbox-checked");
    } else {
      $(this.parentNode).addClass("chkbox-checked");
    }

Solution

  • I think the simplest solution could be like you should use toogleClass() of jQuery. Kindly refer the following code.

    $("#id_of_radioButton").click(function(){
      $("#id_of_parentNode").toggleClass("classname");
    });