views:

56

answers:

7

re,

I have a simple query that works:

$("#test > fieldset > input").each(function() { })

However, I want to select "input" and "select" elements without having to write 2 "each" queries. Is this possible?

thanks.

A: 
$("#test > fieldset > :input").each(function() { })

See here: http://api.jquery.com/input-selector/

RPM1984
This is incorrect. It matches more than those two elements.
cletus
+1  A: 

Oy! There's the documentation for that!

ivans
+2  A: 

jQuery has some Good documentatiion

$("input, select").each(function() { })
Pablo
Pablo, this does not filter children input/select elements in #test>fieldset
MarkL
i know, i just gave the idea of comma separated selectors. Spoon feeding spoil devs.
Pablo
+2  A: 

The somewhat verbose solution is:

$("#test > fieldset > input, #test > fieldset > select").each(function() {
  // do stuff
});

or:

$("#test > fieldset > input").add("#test > fieldset > select").each(function() {
  // do stuff
});

The :input selector will match more than <input> and <select> elements (eg <textarea>).

cletus
+1  A: 

jQuery provides some nice extensibility features. Here's a generic filter to select by multiple tag names:

/*
 * element: the current element being matched
 * index: index of the current element
 * match: parse tokens from the filter string
 *
 * match[0] -> full filter string
 * match[1] -> filter name
 * match[2] -> ""
 * match[3] -> filter parameter
 */
jQuery.expr[':'].tags = function(element, index, match) {
    var inputs = match[3].split(',');
    var nodeName = element.nodeName.toLowerCase();
    return $.inArray(nodeName, inputs) !== -1;
};​​​​​

It has a performance hit in that the callback function will be called for each element matching upto the point of the filter, so I wouldn't recommended this for very large documents.

$("#test > fieldset > :tags(input,select)").hide();
Anurag
Nice one, though I suspect it will prove more useful to allow `:is(...)` as a selector, similar to `$('...').is('...')`.
Kobi
@Kobi - an `:is` filter certainly looks a lot more flexible. It's amazing how much work is actually done with these simple strings :).
Anurag
Very nice. Kobi's and Anurag's solutions are the ones I'd go with; very elegant.
MarkL
+3  A: 
$("#test > fieldset").children("input, select")

Here we first locate the <fieldset>, and then all <input> and <select> elements directly under it. find will work similarly, but will go through the tree, not just direct children.

Kobi
Honestly, I'd like to see syntax like `#test > div > (b, input)`.
Kobi
@Kobi, you could always use `#test > div > :not(:not(b, input))` ;P
Alconja
A: 

You Can Use

$(document).ready(function(){
$("input, select").each(function() { 
 //do ur stuff
});
});
Kailash Yadav