Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  141] [ 1]  / answers: 1 / hits: 23944  / 13 Years ago, tue, june 21, 2011, 12:00:00

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


More From » jquery

 Answers
39

How about this?



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

[#91604] Sunday, June 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaidyn

Total Points: 633
Total Questions: 102
Total Answers: 100

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
jaidyn questions
Fri, Feb 11, 22, 00:00, 2 Years ago
Fri, May 14, 21, 00:00, 3 Years ago
Wed, Oct 30, 19, 00:00, 5 Years ago
;