从已知的父元素中按类名查找元素 [英] Find an element by class name, from a known parent element
问题描述
我想通过类名称找到一个元素.我知道它会出现在特定的父div中,因此,我只想搜索特定的div,而不是搜索整个dom.我正在尝试这样做,但似乎不是正确的语法:
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:
var element = $("#parentDiv").(".myClassNameOfInterest");
什么是正确的方法?
谢谢
推荐答案
您已经关闭.您可以这样做:
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");
...将jQuery对象的上下文设置为#parentDiv
.
...which sets the context of the jQuery object to the #parentDiv
.
此外,如果您使用div.myClassNameOfInterest
而不是.myClassNameOfInterest
,则在某些浏览器中可能会更快.
Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest
instead of just .myClassNameOfInterest
.
这篇关于从已知的父元素中按类名查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!