jQuery: add div if it does not exist?

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




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

1 answer

  • answered 2018-01-11 21:03 j08691

    You check the length.


    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)