TruMan1
TruMan1

Reputation: 36098

Consolidate multiple jQuery conditional statements to a single query?

On my web page, I output jQuery for each record that is rendered on the page like this:

if ($.trim($('#attachment<%# Eval("Id")%> .content').html()) == '') {
  $('#attachmentClick<%# Eval("Id")%>').hide();
}

Notice there is server binding on the element ID to make sure each record has the jQuery processed. Is there a way to do this only once on the page by embedding the conditional statement, such as "for all $(this.ID + ' .attachmentsClick'), hide only if $('.attachments.content').html() trimmed is blank"?

Upvotes: 4

Views: 444

Answers (2)

Spycho
Spycho

Reputation: 7788

You could use jQuery's filter function to reduce the set of potential elements to those with empty content, and then hide them:

$('.attachmentsClick').filter(function(){
    return $.trim($(this).find('.content').html()) == '';
}).hide();

This assumes that you give the class of "attachmentsClick" to all of your row elements. It does not need the ID of the row elements. Just run this after your content has loaded, and it will hide all elements with a class of "attachmentsClick" that have a child with a class of "content" which is empty when trimmed.

Your HTML might look something like:

<div class="attachmentsClick"><!-- this one will be hidden -->
  <div class="content"></div>
</div>

<div class="attachmentsClick"><!-- this one will be hidden too -->
  <div class="content">     </div>
</div>

<div class="attachmentsClick"><!-- this one will NOT be hidden -->
  <div class="content"><p>some content<p></div>
</div>

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190952

You can use .each(). .someCommonClass should be on each one that has the ID.

$('.someCommonClass').each(function(i, e) {
   var $e = $(e);
   if ($.trim($('.content', $e).html()) == '')
       $e.hide();
});

Upvotes: 1

Related Questions