1

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.

6 Answers 6

3
$("#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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

jQuery has some Good documentatiion

$("input, select").each(function() { })

2 Comments

Pablo, this does not filter children input/select elements in #test>fieldset
i know, i just gave the idea of comma separated selectors. Spoon feeding spoil devs.
2

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>).

Comments

1

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();

3 Comments

Nice one, though I suspect it will prove more useful to allow :is(...) as a selector, similar to $('...').is('...').
@Kobi - an :is filter certainly looks a lot more flexible. It's amazing how much work is actually done with these simple strings :).
Very nice. Kobi's and Anurag's solutions are the ones I'd go with; very elegant.
1

Oy! There's the documentation for that!

Comments

0

You Can Use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.