wotney
wotney

Reputation: 1046

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

Upvotes: 0

Views: 815

Answers (3)

Ishan Shah
Ishan Shah

Reputation: 393

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

Upvotes: 1

Aplet123
Aplet123

Reputation: 35502

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.

Upvotes: 1

Mamun
Mamun

Reputation: 68933

$(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');

Upvotes: 1

Related Questions