A neat way to implement a custom jquery filter (selection based on parent class)?

I want to select every text field in which there is no DIV with a red class among my parents, do something for everyone, and then do something else with the rest of the textareas on the page. In other words, select a set of elements, work only with some of them, and then do something else with the rest.

I know I can do something like below, but is there a less awkward way to do this?

$('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!

+4
source share
5 answers

What is wrong with that? jQuery is powerful, but there is something to be said to keep the code clean and readable, rather than trying to be too smart.

 $('textarea').each(function() { if ($(this).parent('div.red').length > 0) { $(this).css('border', 'solid 1px red'); } else { $(this).css('border', 'solid 1px green'); } } 
+5
source

perhaps not the most efficient, but rather intuitive

 $('textarea').css('border', '1px solid green'); $('div.red textarea').css('border', '1px solid red'); 

although something like this might be more in css if you try to apply it to all text fields at any time:

 textarea { border: 1px solid green; } div.red textarea { border: 1px solid red; } 

Edit:

As Paolo Bergantino notes, if you want to do something more complex than one css command in text areas, you can use

 var redAreas = $('div.red textarea'); var otherAreas = $('textarea').not(redAreas); 
+5
source
 $("textarea").not("div.Red textarea"); /* textareas which do not have a div with class Red among its parents */ $("div.Red textarea"); /* textareas which have a div with class Red amoung its parents */ 
+2
source

I don't know if this is better, but you can try.

 $('textarea').each(function() { var borderColor = $(this).parents('div.red').length > 0 ? 'red' : 'green'; $(this).css('border', '1px solid ' + borderColor); }); 
0
source

What is wrong with using CSS?

 textarea { border: 1px solid green; } div.red textarea { border: 1px solid red; } 
0
source

All Articles