Reputation: 3903
I have three columns, each of them containing a DIV
. These DIV
's are filled with data but it occasionally happens, that these DIV
's are empty and in that case they screw up my layout. Now I want to check if the DIV
's are filled with data (html) and if not, to remove them. I made some if
-statements but I'm sure this can be done smoother.
Here is my js code:
if ($.trim($(".fcol1").html()) =='') {
$(".fcol1").remove();
}
if($.trim($(".fcol2").html()) == '') {
$(".fcol2").remove();
}
if($.trim($(".fcol3").html()) == '') {
$(".fcol3").remove();
}
So, is there a way to shorten this code?
Upvotes: 1
Views: 326
Reputation: 1074276
If they're truly empty, you can do:
$(".fcol1:empty, .fcol2:empty, .fcol3:empty").remove();
...but if they have even a blank text node in them, that won't work. You could do:
$(".fcol1, .fcol2, .fcol3").filter(function() {
return !$.trim(this.innerHTML);
}).remove();
Note that your original code only checks the first element matching the selector and, if that one element is empty, deletes all matching elements whether they're empty or not. E.g., if the first .fcol1
is empty, all .fcol1
s are deleted. (Perhaps you probably only have one of each...)
Upvotes: 6