Question

I want an if else statement which checks if the class .post-single exists and then if it exist execute code:

single = $('.post-single').height();
tab = $('#tab');
tab_height = tab.height();
footer_height = $('footer').height();
max_top = (single + 323) - (tab_height);
tab_offset = tab.offset();

and if it does not exist execute this the same code but, with a different class

single = $('.wrap content').height();
tab = $('#tab');
tab_height = tab.height();
footer_height = $('footer').height();
max_top = (single + 323) - (tab_height);
tab_offset = tab.offset();
Was it helpful?

Solution

Try to use the element's length property to check its presence,

if($('.post-single').length) {
 //exist
}
else {
 //not exist
}

Full code,

single =($('.post-single').length) ? $('.post-single').height() : $('.wrap content').height();  
tab = $('#tab');
tab_height = tab.height();
footer_height = $('footer').height();
max_top = (single + 323) - (tab_height);
tab_offset = tab.offset();

OTHER TIPS

Use length property like below

if($(".post-single").length > 0)
  alert(".post-single exist");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top