Puyol
Puyol

Reputation: 3109

Add content if element is not empty

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.

Upvotes: 14

Views: 40600

Answers (6)

Starx
Starx

Reputation: 79021

Use length to check instead.

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

Upvotes: 1

Vimalnath
Vimalnath

Reputation: 6463

Try this:

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

OR:

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

Upvotes: 0

user1056272
user1056272

Reputation:

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

Upvotes: 5

Shikiryu
Shikiryu

Reputation: 10219

You got an unclosed <p> and to get the selector's html, you use a function, not an attribute :

$(this).html()

your fiddle http://jsfiddle.net/bCKGV/

mine http://jsfiddle.net/bCKGV/1/

Upvotes: 0

Evan Mulawski
Evan Mulawski

Reputation: 55324

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

jQuery empty selector

Upvotes: 23

Chuck Norris
Chuck Norris

Reputation: 15200

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

Upvotes: 5

Related Questions