Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - create element if doesn't exist - a shorter way

How can I find out if a certain element has another element as a child? And if it doesn't, append a new one to it and then return it.

I tried it with:

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

but even though it creates my element if it doesn't exist, it doesn't return it...

like image 244
Alex Avatar asked Jun 21 '11 02:06

Alex


3 Answers

How about this?

var myel = $('> div.my', this).length ? $('> div.my', this) : $('<div class="my"></div>').css('opacity', 0).appendTo(this);
like image 157
glortho Avatar answered Nov 15 '22 18:11

glortho


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 that you only need to query the children once, so if there is a lot of children, this will save some time.

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

like image 25
Alastair Pitts Avatar answered Nov 15 '22 19:11

Alastair Pitts


Similar to Alastair's method, but using filters:

$('div.outerDiv:not(:has(div.my))').each(function(){
  $('<div class="my"></div>')
    .appendTo(this)
    .css('opacity', 0);
});
like image 3
kinakuta Avatar answered Nov 15 '22 20:11

kinakuta