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
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")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With