1

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?

1
  • Add more description? Commented Sep 30, 2015 at 13:06

1 Answer 1

6

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 .fcol1s are deleted. (Perhaps you probably only have one of each...)

Sign up to request clarification or add additional context in comments.

2 Comments

Or for futur readers, could use :blank too in CSS4 to handle any white spaces drafts.csswg.org/selectors-4/#the-blank-pseudo
This is awesome! Thanks alot! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.