May 4, 2012

Add content if element is not empty

Question by Puyol

HTML:

<div id="parent"> 
  <div class="child"></div> 
  <div class="child"><p>Div with content<p></div> 
  <div class="child"><img scr="pic.png" alt="Div with picture" /></div>
</div>

Result I want:

<div id="parent"> 
  <div class="child"></div> 
  <div class="child"><h1>title</h1><p>Div with content<p></div> 
  <div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>

My jQuery code:

$(".child").each(function() {
    if ($(this).html != '')
        $(this).prepend('<h1>title</h1>');
});

Result with my jQuery code:

<div id="parent"> 
  <div class="child"><h1>title</h1></div> 
  <div class="child"><h1>title</h1><p>Div with content<p></div> 
  <div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>

So I just want to add a title to every div of a certain class that’s not empty.

Answer by Evan Mulawski

$(".child:not(:empty)").prepend('<h1>title</h1>');

jQuery empty selector

Answer by Starx

Use length to check instead.

$(".child").each(function() {
    if ($(this).html().length)
        $(this).prepend('<h1>title</h1>');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!