7

I've looked around and found a lot of questions about this, but none of the solutions work for me. I have a structure like this:

<div class="pricetag">
    <div class="price">400</div>
</div>

<div class="pricetag">
    <div class="price"></div>
</div>

<div class="pricetag">
    <div class="price">250</div>
</div>

What I want to do is to hide the .pricetag where .price doesn't contain anything. It can be a lot of different .pricetag's on the same page but I just want to hide the ones with empty .price.

Is this possible with jQuery? I've tried a lot of different scripts but none have worked properly.

Tiago Mussi
  • 801
  • 3
  • 13
  • 20
Daniel
  • 1,525
  • 4
  • 12
  • 17

6 Answers6

20

You can use the :empty selector and the parent method, assuming the empty .price elements will never contain any text nodes (e.g. a new line character):

$(".price:empty").parent().hide();

Here's a working example.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • This fixed it! Thank you very much! I've only tried using if statements to check if the div is empty. Thanks again. I'll mark this as the answer as soon as I'm allowed to do it :) – Daniel Jul 02 '12 at 08:56
  • Clever way of doing it. I was unaware of the `:empty` selector. Thanks – Clyde Lobo Jul 02 '12 at 10:04
  • @ClydeLobo - You're welcome :) Just be aware that a single space, or new line, or anything else between the start tag and end tag will count as a text node, which means the `:empty` selector will not match it. – James Allardice Jul 02 '12 at 10:05
  • @JamesAllardice : That I am already aware of. Thanks anyways :) – Clyde Lobo Jul 02 '12 at 10:54
2

This jquery code will do it

$(function(){
  $(".price").each(function(){
    if($(this).html()=="")
      $(this).parent(".pricetag").hide();
  });
});

jsbin example : http://jsbin.com/ovagus

Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61
1
$('.price').each(function(){
  if ($(this).text().length == 0) {
    $(this).parent().hide()
  }
})
Ram
  • 143,282
  • 16
  • 168
  • 197
1

working demo http://jsfiddle.net/mm4pX/1/

You can use .is(':empty') to check if div is empty and then make parent div hidden.

Hope this helps,

code

$('.price').each(function() {
    if $('.price').is(':empty') $(this).parent().hide()
});​
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1

try this jQuery script

$(document).ready(function(e)
{
    $('div.pricetag').each(function(key, value)
    {
        if(!$('div.price', value).html()) $(value).hide();
    });
});
1

The :empty selector does not select a element if it contains whitespaces. If that is a problem then you can trim the element from whitespaces:

function isEmpty(element){
  return !$.trim(element.html())
}

$(".box").each(function() {
  var box = $(this);
  var body = box.find(".box-body");

  if(isEmpty(body)) {
    console.log("EMPTY");
    box.hide();
  } 
});

http://codepen.io/DanAndreasson/pen/jWpLgM

Dan Andreasson
  • 15,380
  • 5
  • 29
  • 30