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

719 Views Asked by At

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

There are 3 best solutions below

0
On BEST ANSWER

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");
});
0
On

$(this.parentNode) is a jQuery object, as classList is pure JS property, this will not work on jQuery referenced object.

Try using jQuery's .attr():

$(this.parentNode).attr('class');
0
On

Don't blindly use jQuery for everything. this.parentNode.classList will be defined because it's not wrapped in jQuery, since classList doesn't exist in jQuery.