Search code examples
jqueryif-statementstringis-empty

jquery if tag is empty then write text - seems to not use if statement and applies to all tags whether empty or not


I've tried many different ways to do this, and each time it writes .text('FREE') to all tags whether they are empty or not.

I am trying to find all tags that are empty, then write the text "FREE" in the empty tag.

If an em tag is not empty, it will be a dollar value such as "$8.00". If it is a dollar amount then I want it to not do anything to it. Could this be something related to having a dollar sign inside the tag?

<script type="text/javascript">
    $( document ).ready(function() {
        if ($(".ProductPriceRating em").length == 0) {
            $(".ProductPriceRating em").text('FREE');
        }

     });
</script>

I will continue to try other things, but any input or education would be so appreciated, thanks much!


Solution

  • You can use the :empty selector for this:

    $(document).ready(function() {
        $(".ProductPriceRating em:empty").text("FREE");
    });
    

    $(selector).length returns the number of elements matching the selector, not the size of the contents.