boszlo
boszlo

Reputation: 1286

if / else in jquery

Really struggling with this simple code here. I'm checking if the section with #setactionsuccess exists if not I want to create it and prepend it to the container. First part works smooth but it never goes to 'else' (and the condition is met - I triple checked that). Any help greatly appreciated.

if ($('#setactionsuccess')){
    var currenttime = new Date();
    $('#setactionsuccess').empty();
    $('#setactionsuccess').html('<h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p>');
} else {
    console.log('here');
    var string = '<section class="successful" id="setactionsuccess"><h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p></section>';
    console.log(string);
    $('#currentsets').prepend(string);
}

Upvotes: 1

Views: 3564

Answers (6)

JeskTop
JeskTop

Reputation: 481

if ($(selector).length)

You can check by this code.

Upvotes: 0

Edward Ruchevits
Edward Ruchevits

Reputation: 6696

If you always have block with id #setactionsuccess and you need to check, if it is empty, that is correct solution:

if ($('#setactionsuccess'.text().length != 0)){
    var currenttime = new Date();
    $('#setactionsuccess').empty();
    $('#setactionsuccess').html('<h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p>');
} else {
    console.log('here');
    var string = '<section class="successful" id="setactionsuccess"><h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p></section>';
    console.log(string);
    $('#currentsets').prepend(string);
}

Upvotes: 0

Parv Sharma
Parv Sharma

Reputation: 12705

if ($('#setactionsuccess')) always returns true
because javascript cheks for null and undefined and jquery never returns a null or undefined even when any element with id setactionsuccess dosent exists
try looking for length for the selector $('#setactionsuccess').length

Upvotes: 1

billyonecan
billyonecan

Reputation: 20270

You can check if the element exists by using length

if($('#setactionsuccess').length) {
   ...
}

Upvotes: 1

Johni
Johni

Reputation: 2959

You get always something from a selector even if there are no matches. You hav to check the number of matches against 0.

Upvotes: 1

gaurang171
gaurang171

Reputation: 9090

try this

if($('#setactionsuccess').length > 0)

Upvotes: 5

Related Questions