jQuery 从已知的父元素中按类名查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3034699/
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
Find an element by class name, from a known parent element
提问by user246114
I want to find an element by class name. I know it will appear in a particular parent div, so rather than search the entire dom, I'd like to search only the particular div. I am trying this, but does not seem to be the correct syntax:
我想按类名查找元素。我知道它会出现在特定的父 div 中,所以我不想搜索整个 dom,我只想搜索特定的 div。我正在尝试这个,但似乎不是正确的语法:
var element = $("#parentDiv").(".myClassNameOfInterest");
what's the right way to do that?
这样做的正确方法是什么?
Thanks
谢谢
回答by user113716
You were close. You can do:
你很接近。你可以做:
var element = $("#parentDiv").find(".myClassNameOfInterest");
.find()
- http://api.jquery.com/find
.find()
- http://api.jquery.com/find
Alternatively, you can do:
或者,您可以执行以下操作:
var element = $(".myClassNameOfInterest", "#parentDiv");
...which sets the context of the jQuery object to the #parentDiv
.
...将 jQuery 对象的上下文设置为#parentDiv
.
EDIT:
编辑:
Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest
instead of just .myClassNameOfInterest
.
此外,如果您这样做div.myClassNameOfInterest
而不仅仅是.myClassNameOfInterest
.
回答by Jared I
var element = $("#parentDiv .myClassNameOfInterest")