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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:16:45  来源:igfitidea点击:

jquery - get elements by tag within a specific div?

jquerygetelementsbytagname

提问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 lengthproperty in the if().

您的if()测试将始终评估true. 您应该lengthif().

var uform = $('#umi-form');
if(uform.length) {
    var inputs = uform.find('input');
}

If you were hoping to get a nodeListinstead of a jQuery object, do this:

如果您希望获得nodeListjQuery 对象而不是 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 inputs in the document("page"). Whilst

将获得( "page")input中的所有s 。同时document

document.getElementById( 'umi-form' ).getElementsByTagName( 'input' );

will get all the inputs in #umi-form.

将得到所有的inputs #umi-form

In this case, the calling of getElementsByTagNameis on the elementbefore the period. If we call it on the documentwe 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 indexis 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 有一个很好的了解。