Learning
Learning

Reputation: 20001

Hide only those spans which are empty or have no text in them

I need to hide only those spans which don't have any text.

<div class="img-wrapper">
    <div class="showcase-caption" style="display: block; "> <span id="MainContent_ImageCaption_0">This has caption</span>

    </div>
    <div class="showcase-caption" style="display: block;">  <span id="MainContent_ImageCaption_1"></span>

    </div>
    <div class="showcase-caption" style="display: block;">  <span id="MainContent_ImageCaption_2">This has caption and show show</span>

    </div>
    <div class="showcase-caption" style="display: block;">  <span id="MainContent_ImageCaption_3"></span>

    </div>
</div>

http://fiddle.jshell.net/0mzpLrt3/

Upvotes: 5

Views: 2128

Answers (4)

Benjamin Ray
Benjamin Ray

Reputation: 1870

You could make a slight change to your JavaScript (in the fiddle) to remove or hide the parent of the empty element:

$(".img-wrapper span:empty").each( function () {
    $(this).parent().remove(); // or .hide() to hide
});

Upvotes: 9

Ben Pearce
Ben Pearce

Reputation: 7094

Fiddle

Html:

<div class="img-wrapper">
    <div class="showcase-caption" > <span id="MainContent_ImageCaption_0">This has caption</span>

    </div>
    <div class="showcase-caption">  <span id="MainContent_ImageCaption_1"></span>

    </div>
    <div class="showcase-caption">  <span id="MainContent_ImageCaption_2">This has caption and show show</span>

    </div>
    <div class="showcase-caption" > <span id="MainContent_ImageCaption_3"></span>

    </div>
</div>

JS:

$(".img-wrapper span:empty").each( function () {
    $(this).parent().addClass("hide");
});

Upvotes: 0

Paulo Filipe Dantas
Paulo Filipe Dantas

Reputation: 111

You can use something like this

$(".img-wrapper .showcase-caption span").each(function(){
      if ($(this).is(':empty')) 
          $(this).parent().hide()
});

I'm test in http://fiddle.jshell.net/0mzpLrt3/ and works fine

Upvotes: 0

radiaph
radiaph

Reputation: 4081

Use the :empty pseudo class selector:

span:empty {
    display: none; /* or visibility: hidden */
}

Upvotes: 4

Related Questions