Safeena
Safeena

Reputation: 403

add class to a child dynamically

<li class="view">
    <a href="#"><span>Settings</span> </a>
    <ul >
      <li ><a>Leave Settings</a></li > 
      <li ><a href="compansatorysetting.aspx">Compensatory Settings</a></li>
    </ul>
</li>

I want to add a class="open" in <ul> when i click the <li>.

I am using

$(".view").click(function () { 
   $(this).children().addClass("open"); 
});

It is not working. Any solution?

Upvotes: 1

Views: 735

Answers (4)

Vivek Gupta
Vivek Gupta

Reputation: 1055

You are using wrong class

$(".view").click(function () {
    $(this).children().addClass("open");
});

Upvotes: 0

Manoz
Manoz

Reputation: 6617

A more convenient and shorter way would be-

$('.view').click(function(){
  $('>ul',this).addClass('open');                     
});

Example

Upvotes: 0

ajaykumartak
ajaykumartak

Reputation: 776

If you want to assign open class to only ul then use following code.

$(".view").click(function () { 
  $(this).children('ul').addClass("open"); 
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82251

You need to use .parent() or .closest('ul') for traversing to parent ul element:

$(".view").click(function () { 
  $(this).parent().addClass("open"); 
});

If you are looking to target inner ul elements inside clicked li, then use .find() selector:

$(".view").click(function () { 
  $(this).find('ul').addClass("open"); 
});

Upvotes: 4

Related Questions