Yetimwork Beyene
Yetimwork Beyene

Reputation: 2337

how to add content to first empty div or insert after if not empty using jquery?

I have the following content...

              <div class="sectionA"></div>
              <div class="sectionA"></div>
              <div class="sectionA"></div>
              <div class="sectionA"></div>

First, I need to append content to the first empty div.... So I attempted this:

              if(".sectionA").is(":empty"))
              {
                   alert("empty div")
                   $(this).append(value);
              }else // if no available empty divs then insert after last div
              {
                   $(".sectionA:last").after("<div>"+value+"</div>");
              }

This logic is not working and the alert("empty div") test never gets trigger and I know there are empty divs as verified through Firebug.. Any idea what I'm doing wrong here?

Upvotes: 0

Views: 1256

Answers (2)

Devang Rathod
Devang Rathod

Reputation: 6736

If you need to append content to the first empty div. you missed $ sign in if condition

$(document).ready(function(){
  if($(".sectionA:first").is(":empty"))
  {
       alert("empty div")
       $(this).append(value);
  }else // if no available empty divs then insert after last div
  {
       $(".sectionA:last").after("<div>"+value+"</div>");
  } 
});

So after that you will gets alert("empty div") test trigger. after that you can perform your logic to append value.

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220006

You have a syntax error:

if ( $(".sectionA").is(":empty") )
// ^ ^ You're missing the parentheses & dollar sign.

However, your logic is flawed. Use this instead:

var $sections = $(".sectionA");
var $empty = $sections.filter(':empty');

if ( $empty.length ) {
    $empty.first().append(value);
} else {
    $sections.last().after('<div>' + value + '</div>');
}

Upvotes: 2

Related Questions