eozzy
eozzy

Reputation: 68710

addClass if ul exists (jQuery)

I'm building a simple dropdown where I'd like to add a class to parent if UL exists:

HTML:

<ul id="menu">
  <li><a href="#">Parent 1</a></li>
  <li><a href="#">Parent 2</a>
    <ul>
      <li><a href="#">Sub 2.1</a></li>
      <li><a href="#">Sub 2.2</a></li>
    </ul>
  </li>
</ul>

So I'd like to:

This isn't quite working, not sure why:

$(function () {
    $("ul#menu li").hover(function () {
        $(this).addClass("hover");
        $('ul:first', this).css('visibility', 'visible');
    },
    function () {
        $(this).removeClass("hover");
        $('ul:first', this).css('visibility', 'hidden');
    });
    $("ul#menu li ul li:has(ul)").find("a:first").addClass("dropdown");
});

Many thanks for your help!

Upvotes: 2

Views: 4286

Answers (3)

David Hellsing
David Hellsing

Reputation: 108500

var ul = $('#menu');

if (ul.length) {
    ul.children('li').hover(function() {
        $(this).children('ul').show();
    }, function() {
        $(this).children('ul').hide();
    }).children('ul').hide().parent().addClass('dropdown');
}

Demo: http://jsbin.com/ofayu

BTW: you are closing the <li> tags incorrectly in your markup.

Upvotes: 2

Victor Nicollet
Victor Nicollet

Reputation: 24577

You wrote:

$("ul#menu li ul li:has(ul)")

Given your HTML structure, shouldn't this be:

$("ul#menu li:has(ul)")

Upvotes: 1

Will Vousden
Will Vousden

Reputation: 33378

This should do the trick (untested):

$('ul#menu > li > ul').each(function()
{
    var list = $(this);
    list.hide();
    list.parent().hover(list.hide, list.show);
    list.parent().parent().addClass('dropdown');
});

Upvotes: 0

Related Questions