jquery - 通过特定div中的标签获取元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4443202/
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
jquery - get elements by tag within a specific div?
提问by newbie-shame
I'm trying to get all input elements within a certain div, but it seems to return all inputs on any given page... is there a way to do this?
我试图在某个 div 中获取所有输入元素,但它似乎返回任何给定页面上的所有输入......有没有办法做到这一点?
if($('#umi-form')) {
var inputs = document.getElementsByTagName('input');
}
回答by treeface
It can be done like this:
可以这样做:
var $inputs = $('#umi-form input');
回答by user113716
Your if()
test will always evaluate true
. You should use the length
property in the if()
.
您的if()
测试将始终评估true
. 您应该length
在if()
.
var uform = $('#umi-form');
if(uform.length) {
var inputs = uform.find('input');
}
If you were hoping to get a nodeList
instead of a jQuery object, do this:
如果您希望获得nodeList
jQuery 对象而不是 jQuery 对象,请执行以下操作:
var uform = $('#umi-form');
if(uform[0]) {
var inputs = uform[0].getElementsByTagName('input');
}
回答by Fred Gandt
JavaScript first...
首先是 JavaScript...
document.getElementsByTagName( 'input' );
will get all the input
s in the document
("page"). Whilst
将获得( "page")input
中的所有s 。同时document
document.getElementById( 'umi-form' ).getElementsByTagName( 'input' );
will get all the input
s in #umi-form
.
将得到所有的input
s #umi-form
。
In this case, the calling of getElementsByTagName
is on the elementbefore the period. If we call it on the document
we get all the elements with the named tag on the page. If we call it on a childelement of the document
, then we get only the elements with the named tag from within that child.
在这种情况下,调用的getElementsByTagName
是句点之前的元素。如果我们把它在document
我们得到了所有与上指定的标记元素页面。如果我们在 的子元素上调用它document
,那么我们只会从该子元素中获取带有命名标签的元素。
You'll always get all the elements with the named tag that are within the elementthe method is called on. If however you want to get at just one of them, use
您将始终获得调用该方法的元素内具有命名标记的所有元素。但是,如果您只想获得其中之一,请使用
target_element.getElementsByTagName( 'tag-name' )[ index ];
where index
is an integerwithin the range of the returned length
, which is obtained with
其中index
是返回范围内的整数length
,通过
target_element.getElementsByTagName( 'tag-name' ).length;
Since jQuery is a JavaScript library, it's advisable to get a good understanding of JS before attempting to use jQuery IMO.
由于 jQuery 是一个 JavaScript 库,因此在尝试使用 jQuery IMO 之前,最好对 JS 有一个很好的了解。