开发者

jQuery if element does not contain element then create and append one?

开发者 https://www.devze.com 2023-03-31 05:37 出处:网络
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 e

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>'));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消