javascript addClass("test") 给出错误:TypeError: undefined is not a function
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23228760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
addClass("test") give error: TypeError: undefined is not a function
提问by Alex
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>
我想为 parent 添加 css 类span
,为 tag<li>
I tried like this:
我试过这样:
$(".myCssClass")[0].parentNode.addClass("test")
TypeError: undefined is not a function
I use Jquery 1.5.2
我使用 Jquery 1.5.2
回答by Oriol
addClass
is a method of jQuery objects. When you use $(".myCssClass")[0]
, you have the real element, not the jQuery wrapper.
addClass
是 jQuery 对象的方法。当您使用 时$(".myCssClass")[0]
,您拥有真正的元素,而不是 jQuery 包装器。
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")
再次将其包装到 jQuery 对象中:
$($(".myCssClass")[0].parentNode).addClass("test")
仅适用于 jQuery 对象:
$(".myCssClass").eq(0).parent().addClass("test")
使用纯 JavaScript 添加类(旧浏览器不支持):
$(".myCssClass")[0].parentNode.classList.add("test")
回答by Krishna
Use .parent()
利用 .parent()
$(".myCssClass").parent().addClass("test")
.addClass()
can only be used against jQuery selectors.
.addClass()
只能用于 jQuery 选择器。
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 对象,要转换成一个你需要$()
像这样包装的对象
$($(".myCssClass")[0].parentNode)
//jQuery selector
$($(".myCssClass")[0].parentNode)
//jQuery选择器
now addClass()
, $($(".myCssClass")[0].parentNode).addClass("test")
现在addClass()
,$($(".myCssClass")[0].parentNode).addClass("test")