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

Viewed 23389

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...

4 Answers
Related