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

StackOverflow https://stackoverflow.com/questions/23161822

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!

有帮助吗?

解决方案

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.

其他提示

That's because you're basing the if on the number of elements returned by that selector, not the text of individual elements. Instead use the callback, which iterates over each element returned by the selector and can perform an action/assessment on each individual item:

$(".ProductPriceRating em").text(function(i, t) {
    return t.length === 0 ? 'FREE' : t;
});

Simple JS Fiddle demo.

You could conceivably use css for this (depending on your need to support old IE), if the HTML is:

<div class="ProductPriceRating"> <!-- only the class-name matters -->
    <em></em>
</div>

Then css:

.ProductPriceRating em:empty::before {
    content: 'FREE';
}

Simple JS Fiddle demo.

References:

How about this:

$(".ProductPriceRating em:empty").text('FREE');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top