[ACCEPTED]-jQuery - create element if doesn't exist - a shorter way-jquery-selectors

Accepted answer
Score: 20

How about this?

var myel = $('> div.my', this).length ? $('> div.my', this) : $('<div class="my"></div>').css('opacity', 0).appendTo(this);

0

Score: 5

This is how I would do it:

var myDivs = $('div.container').children('div.my');
if(myDivs.length === 0){
    myDivs = $('<div class="my"></div>   ')
        .appendTo('div.container')
        .css('opacity', 0);     
}

My reasoning is 5 that you only need to query the children 4 once, so if there is a lot of children, this 3 will save some time.

Also, if there is no 2 children, then you create one, appendTo the container, perform 1 css and then return it.

Score: 3

Similar to Alastair's method, but using 1 filters:

$('div.outerDiv:not(:has(div.my))').each(function(){
  $('<div class="my"></div>')
    .appendTo(this)
    .css('opacity', 0);
});
Score: 0

Late I know, but a different approach, adding 2 syntactic sugar and making things legible 1 IMO:

function ifNotExists($x){
    if(!$x || $x.length === 0) return { create : function(newX){ return newX; }}
    else return { create : function(){ return $x } };
}

//usage:
$someDiv.append(ifNotExists("div.child").create("<div class='child'>"));

More Related questions