I want to select every textarea that does not have a DIV with class red among its parents, do something to each, and then do something else with the rest of textareas on the page. In other words, select a set of elements, work on only some of them, and then do something else with the rest.
I know I can do something like below, but is there a less clumsy way of doing it?
$('textarea').filter(function() {
return $(this).parents("div.red").length > 0;
}).css('border','1px solid red').end().filter(function() {
return $(this).parents("div.red").length == 0;
}).css('border','1px solid green');
Thanks!
What's wrong with this way? jQuery is powerful, but there is something to be said for keeping code clean and readable and not trying to be too clever.
$('textarea').each(function() {
if ($(this).parent('div.red').length > 0) {
$(this).css('border', 'solid 1px red');
} else {
$(this).css('border', 'solid 1px green');
}
}
maybe not the most efficient, but fairly intuitive is
$('textarea').css('border', '1px solid green');
$('div.red textarea').css('border', '1px solid red');
although something like this may belong more in css if you are trying to apply it to every textarea at all times:
textarea {
border: 1px solid green;
}
div.red textarea {
border: 1px solid red;
}
Edit:
As Paolo Bergantino mentions, if you want to do something more complex than one css command on the textareas you can use
var redAreas = $('div.red textarea');
var otherAreas = $('textarea').not(redAreas);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With