user3108268
user3108268

Reputation: 1083

jQuery: add div if it does not exist?

I know how to addClass if it does not exist e.g.

$("ul:not([class~='bbox'])").addClass("bbox");

Or

if(!$("ul").hasClass("class-name")){
    $("ul").addClass("bbox");
 }

But how do I check if ul element itself with a class already exist and if ul doesn't exist then add one?

Upvotes: 1

Views: 80

Answers (1)

j08691
j08691

Reputation: 208030

You check the length.

Ex:

if( $("ul.class-name").length ){
    //do something
}

If there are no matches, length will be zero and thus false (or falsy), otherwise it will be true (or truthy)

Upvotes: 8

Related Questions