Reputation: 1286
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
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
Reputation: 12705
if ($('#setactionsuccess'))
always returns true
because javascript cheks for null
and undefined
and jquery never returns a null
or undefine
d even when any element with id setactionsuccess dosent exists
try looking for length for the selector $('#setactionsuccess').length
Upvotes: 1
Reputation: 20270
You can check if the element exists by using length
if($('#setactionsuccess').length) {
...
}
Upvotes: 1
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