0

I'm trying to execute a JQuery function that will unput text in an empty div (if it is empty) for each element under the div id "answerrr" however the script will only search for the first div and add text to that, and it disregards the rest. Perhaps I'm using the .each() function incorrectly?

<b><div id="answerrr"></div></b>

<b><div id="answerrr"><p>Not Empty</p></div></b>

<b><div id="answerrr"></div></b>
<script>
  $('#answerrr').each(function() {
    if ($('#answerrr').is(":empty")) {
      $('<p>Empty!</p>').appendTo($(this));
    }
  });
</script>

http://jsfiddle.net/wdTH2/3/

Also, if my page were to load more content through Ajax, how would I go about ensuring that this script is re-executed

0

2 Answers 2

2

Your fundamental problem is that it's not legal in HTML for multiple elements to have the same ID. Use a class instead.

Having fixed that, don't use the same selector again within the .each call, just use $(this) to refer to the current element.

You can also remove the :empty test from within the loop and just make it part of the selector, and since .append will happily work on multiple elements you can in fact get rid of the .each loop too, making your entire code just this:

$('.answerrr:empty').append('<p>Empty!</p');

See http://jsfiddle.net/alnitak/L6B56/ for working demo.

For content added later, just make sure the code above is invoked as part of a .done callback from the AJAX load.

Sign up to request clarification or add additional context in comments.

Comments

0

First of all id must be unique. Use classes instead:

html

 <b><div class="answerrr"></div></b>
 <b><div class="answerrr">Not Empty</div></b>
 <b><div class="answerrr"></div></b>

js

$('.answerrr').each(function () {
    if ($(this).is(":empty")) {
        $('<p>Empty!</p>').appendTo($(this));
    }
});

fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.