kylex
kylex

Reputation: 14416

jQuery kill link if li has children

Given the following structure:

<ul>
    <li><a href="example.com>1</a></li>
    <li><a href="example.com>2</a></li>
    <li><a href="example.com>3</a>
        <ul>
            <li><a href="example.com">3.1</a></li>
            <li><a href="example.com">3.2</a>
                <ul>
                    <li><a href="example.com">3.2.1</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="example.com>4</a></li>
</ul>

I'd like to auto remove or kill the link for 3 and 3.2

Basically any li that has children the link should be removed. What's the best way to go about this?

Upvotes: 2

Views: 1081

Answers (5)

Stephen
Stephen

Reputation: 3432

$('ul li > ul').parent().children("a").attr("href","#")

Upvotes: 0

yitwail
yitwail

Reputation: 2009

using jQuery,

$('li > a').each(function() {
  if ($(this).siblings().length)
    $(this).remove();
});

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816512

If you don't want to keep the text:

$('li:has(ul) > a').remove();

DEMO

If you want to keep the text, you could use .replaceWith:

$('li:has(ul) > a').replaceWith(function() {
    return $(this).text();
});

DEMO

Upvotes: 7

Naftali
Naftali

Reputation: 146310

$("a").click(function(e){
    if( $(this).parent().children('ul').length > 0 ){
        e.preventDefault(); //prevent the link from being followed
        $(this).remove(); //remove the a element
    }
});

Upvotes: 0

Ionuț Staicu
Ionuț Staicu

Reputation: 22174

Even if I didn't tested, this should work:

$('li').filter(function(){ return $('ul', this).length ? this : ''; }).find('a:first').unwrap('<a></a>')

Upvotes: 1

Related Questions