krick krick - 3 months ago 11
jQuery Question

Is there a more efficient way to combine multiple id selectors each with a child selector in jQuery?

Is there some way to write a jQuery selector for multiple ids that also uses the parent > child selector?

I know I can do this...

$('#checkbox1').click(function() {
// do stuff
});


...or this...

$('#div1 > input[type=checkbox]').click(function() {
// do stuff
});


...or this...

$('#checkbox1, #checkbox2, #checkbox3').click(function() {
// do stuff
});


...but when I combine both, it gets kind of verbose. Is there a more efficient/compact way?...

$('#div1 > input[type=checkbox], #div2 > input[type=checkbox], #div3 > input[type=checkbox]').click(function() {
// do stuff
});

Answer

Use .children()

$("#div1, #div2, #div3").children("input[type=checkbox]").click(function() {
    // do stuff
});
Comments