A
A
Andrey Dontsov2015-11-10 16:51:34
JavaScript
Andrey Dontsov, 2015-11-10 16:51:34

How to write an if check in jQuery?

Good day
Please help me understand and I apologize for the heresy in the example below.

You need to check if div.star-rating does NOT have nested elements, then you need to add div.empty to div.star-rating-wrap

If div.star-rating HAS nested elements then do nothing!

The code below doesn't work as expected, it adds the div.empty but removes the div.star-rating if there is one.
Thank you!

$('div.star-rating').has(function() {
    if($('div.star-rating-wrap:empty')) {
        $('div.star-rating-wrap').html('<div class="empty"></div>');
    }else{
        return false;
    }
});

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vitaly Inchin ☢, 2015-11-10
@AndreyBLG

$('.star-rating-wrap').has('.star-rating:empty')
   .append('<div class="empty" />');

D
dima_horror, 2015-11-10
@dima_horror

if ($('div.star-rating').is(":empty")) {
            $('div.star-rating-wrap').append(
                $("<div/>").addClass('empty')
            );
        };

M
Mikhail, 2015-11-10
Chirskiy @chirskiy_mixail

if (!$('.star-rating').is(':empty')) {
    $('div.star-rating-wrap').append('<div class="empty"></div>');
}

Something like this?
You have a strange approach, of course, why add an empty div, it’s not easier to add a class from which it’s easier to work with CSS and not clog the markup with an empty div.

A
Andrey Dontsov, 2015-11-10
@AndreyBLG

html of this question
I.e. in this case div.empty should NOT be added as div.star-rating-wrap contains div.star-rating

<div class="star-rating-wrap">
    <div class="star-rating">
        <span>1111</span>
    </div>
    <div class="empty"></div>
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question