开发者

How to match "input" and "select" elements in jQuery with 1 query

开发者 https://www.devze.com 2022-12-31 20:53 出处:网络
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\" quer

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 possib开发者_运维技巧le?

thanks.


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


jQuery has some Good documentatiion

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


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


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


Oy! There's the documentation for that!


You Can Use

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号