toast
toast

Reputation: 670

How to delete an element which does not have a certain parent?

I want to delete list items who do not have a parent of ul

This is my HTML:

<div class="yamm-content">
    <div class="row">
        <li> <a href="#">Should be deleted</a>

        </li>
        <li> <a href="#">Should be deleted</a>

        </li>
        <ul id="randomid" class="col-xs-12 col-sm-4">
            <li> <a href="#">menu item</a>

            </li>
            <li> <a href="#">menu item</a>

            </li>
            <li> <a href="#">menu item</a>

            </li>
        </ul>
        <ul id="randomid2" class="col-xs-12 col-sm-4">
            <li> <a href="#">menu item</a>

            </li>
            <li> <a href="#">menu item</a>

            </li>
            <li> <a href="#">menu item</a>

            </li>
        </ul>
    </div>
</div>

and my current script:

if (!$('.nav .yamm-content row li').closest('ul').length == 0) {
    $(this).remove();
}

jsFiddle

The first two list items don't have ul's as parents. So they should be deleted.

Upvotes: 3

Views: 126

Answers (3)

htoniv
htoniv

Reputation: 1668

Here i used Javascript only and it may take some lines of coding. I suggest this may be useful some times when you don't want to go for jquery.

var len = document.getElementsByTagName('li').length;
for (var i=0;i<len;i++)
{
if (document.getElementsByTagName('li')[i].parentNode.nodeName != "UL")
{ 
 document.getElementsByTagName('li')[i].remove();
 i--;
}
}

Here is the fiddle

Upvotes: 0

Arbel
Arbel

Reputation: 30989

Simple: $('li:not(ul > li)').remove();

Demo http://jsfiddle.net/46NdQ/3/

Upvotes: 13

000
000

Reputation: 27227

$('li').filter(function(){return !$(this).closest('ul').length}).remove();

Or

$('li').not($('ul li')).remove();

Upvotes: 3

Related Questions