jQuery if element does not contain element then create and append one?
I have a li
element that I am selecting like this:
var parent_li = $(this).parent();
This element may or may not contain an ul
element. I would like to add a child to the ul
but if there is no ul
element I would like to create and add it first.
I tried:
开发者_如何学编程if( !parent_li.children('ul') )
{
//if the parent list doe not contain
//an UL element, then add one
parent_li.append($('<ul></ul>'));
}
However, I found out that parent_li.children('ul') always returns an object even if it does not have any child ul
elements.
So what do I need to do?
if (parent_li.children('ul').length == 0){
parent_li.append($('<ul></ul>'));
}
As you said, the children
method won't ever return a falsey value. It returns a jQuery object with zero or more matched elements. You have to check the length
instead:
if( !parent_li.children('ul').length )
{
//if the parent list doe not contain
//an UL element, then add one
parent_li.append($('<ul></ul>'));
}
精彩评论