1

Here is my html structure

  <ul>
    <li>Main 1
        <ul>
            <li><a href=''>Child 1-1</a></li>
            <li><a href=''>Child 2-1</a></li>
            <li><a href=''>Child 3-1</a></li>
            <li><a href=''>Child 4-1</a></li>
        </ul>   
    </li>
    <li>Main 2
        <ul>
            <li><a href=''>Child 1-2</a></li>
            <li><a href=''>Child 2-2</a></li>
            <li><a href='' class='selected'>Child 3-2</a></li>
            <li>Child 4-2</li>
        </ul>   
    </li>
    <li>Main 3</li>
</ul>

Now What I need is that on document.ready jquery checks that which <li>'s <a> has class 'selected'. If it finds one it put class 'mainselected' on its parent <li> and a class 'listul' on it <ul> so that the code will look like that

<ul>
    <li>Main 1
        <ul>
            <li><a href=''>Child 1-1</a></li>
            <li><a href=''>Child 2-1</a></li>
            <li><a href=''>Child 3-1</a></li>
            <li><a href=''>Child 4-1</a></li>
        </ul>   
    </li>
    <li class='mainselected'>Main 2
        <ul class='listul'>
            <li><a href=''>Child 1-2</a></li>
            <li><a href=''>Child 2-2</a></li>
            <li><a href='' class='selected'>Child 3-2</a></li>
            <li>Child 4-2</li>
        </ul>   
    </li>
    <li>Main 3</li>
</ul>

Can anyone please give me a jquery code for this.

Thanks

0

2 Answers 2

2
$(function(){     
  $('li a.selected').closest('ul').addClass('listul')
    .parent().addClass('mainselected');    
});
Sign up to request clarification or add additional context in comments.

Comments

1
$(function() {  // on DOM ready
    $("ul > li > ul > li > a.selected")     // explicitly search in nested ul
        .closest("ul").addClass("listul")   // assing ".listul" to parent ul
        .parent().addClass("mainselected"); // assign ".mainselected" to containing li
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.