0

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");
    }
wotney
  • 1,039
  • 3
  • 21
  • 34
  • 1
    `classList` is not a jquery function it is on the native js element - you are mixing up jquery and native js. Use `.hasClass()` instead: https://api.jquery.com/hasClass/ – Pete Apr 09 '20 at 12:43

3 Answers3

1

$(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');
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

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.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

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");
});
Ishan Shah
  • 383
  • 2
  • 8