Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

neat way to implement a jquery custom filter (selecting based on parent's class)?

Tags:

jquery

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!

like image 560
montrealist Avatar asked Dec 18 '22 08:12

montrealist


2 Answers

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');
  }
}
like image 50
Matt Avatar answered May 09 '23 21:05

Matt


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);
like image 25
cobbal Avatar answered May 09 '23 22:05

cobbal