ductinh2405
ductinh2405

Reputation: 21

How to addClass for all parent of an element using jQuery?

Sub Item 3.1.1.4 has class="active". How can I using jQuery to add class="active" for tag a of Folder 3.1.1 and Folder 2.1?

Please help me! Thanks!

<ul>
    <li><a>Folder 2</a>
      <ul>
      <li><a>Sub Item 2.1</a></li>
      <li><a>Folder 2.1</a>
        <ul>
        <li><a>Sub Item 2.1.1</a></li>
        <li><a>Sub Item 2.1.2</a></li>
        <li><a>Folder 3.1.1</a>
            <ul>
                <li><a>Sub Item 3.1.1.1</a></li>
                <li><a>Sub Item 3.1.1.2</a></li>
                <li><a>Sub Item 3.1.1.3</a></li>
                <li><a class="active">Sub Item 3.1.1.4</a></li>
                <li><a>Sub Item 3.1.1.5</a></li>
            </ul>
        </li>
        <li><a>Sub Item 2.1.4</a></li>
        </ul>
      </li>
      </ul>
    </li>
    <li><a>Item 4</a></li>
</ul>

Result in this ex: Folder 3.1.1 => Folder 3.1.1, Folder 2.1 => Folder 2.1

Upvotes: 2

Views: 2434

Answers (1)

David Titarenco
David Titarenco

Reputation: 33386

You want to use $(this).parents().addClass('active').

Read more here: http://api.jquery.com/parents/

Upvotes: 5

Related Questions