Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass("test") give error: TypeError: undefined is not a function

In console I have:

$(".myCssClass")[0].parentNode
<li><span class="myCssClass">some text</span></li>

I want to add css class for parent span, for tag <li>

I tried like this:

$(".myCssClass")[0].parentNode.addClass("test")
TypeError: undefined is not a function

I use Jquery 1.5.2

like image 799
Alex Avatar asked Apr 22 '14 19:04

Alex


2 Answers

addClass is a method of jQuery objects. When you use $(".myCssClass")[0], you have the real element, not the jQuery wrapper.

Then, you can:

  • Wrap it to a jQuery object again:

    $($(".myCssClass")[0].parentNode).addClass("test")
    
  • Only work with jQuery objects:

    $(".myCssClass").eq(0).parent().addClass("test")
    
  • Add class with plain JavaScript (not supported on old browsers):

    $(".myCssClass")[0].parentNode.classList.add("test")
    
like image 176
Oriol Avatar answered Oct 09 '22 18:10

Oriol


Use .parent()

$(".myCssClass").parent().addClass("test")

.addClass() can only be used against jQuery selectors.

Alternative solution (wouldn't recommend this over the top mentioned solution but for the sake of completion)

$(".myCssClass")[0].parentNode is not a jQuery object, to convert into one you need to wrap with $() like this

$($(".myCssClass")[0].parentNode) //jQuery selector

now addClass(), $($(".myCssClass")[0].parentNode).addClass("test")

like image 42
Venkata Krishna Avatar answered Oct 09 '22 20:10

Venkata Krishna