newbie-shame
newbie-shame

Reputation: 243

jquery - get elements by tag within a specific div?

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?

if($('#umi-form')) {
          var inputs = document.getElementsByTagName('input');
}

Upvotes: 5

Views: 36174

Answers (3)

Fred Gandt
Fred Gandt

Reputation: 4312

JavaScript first...

document.getElementsByTagName( 'input' );

will get all the inputs in the document ("page"). Whilst

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

will get all the inputs in #umi-form.

In this case, the calling of getElementsByTagName is on the element before 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 child element of the document, then we get only the elements with the named tag from within that child.

You'll always get all the elements with the named tag that are within the element the 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 integer within the range of the returned length, which is obtained with

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.

Upvotes: 1

user113716
user113716

Reputation: 322612

Your if() test will always evaluate true. You should use the length property in the 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:

var uform = $('#umi-form');
if(uform[0]) {
    var inputs = uform[0].getElementsByTagName('input');
}

Upvotes: 9

treeface
treeface

Reputation: 13351

It can be done like this:

var $inputs = $('#umi-form input');

Upvotes: 13

Related Questions