Home > Software design >  add class to parent ul on sub item click javascript
add class to parent ul on sub item click javascript

Time:08-08

I try to keep my menu open when a sub item with link is open. I have same class name for the parent menu and sub item link. I need the corresponding menu to remain open when sub item is clicked

thank you

here is what I have try so far

 <li >
            <a  data-bs-target="#econ-nav" data-bs- 
                 toggle="collapse" href="#">
                <i ></i><span>finance</span><i 
                     ></i>
            </a>
       <ul id="econ-nav"  data-bs-parent="#sidebar-nav">
                                      
                <li>
                    <a  href="submeni1.html">
                        <i ></i><span>SubMenu1</span>
                    </a>
                </li>
                <li>
                    <a  href="submenu2.html">
                        <i ></i><span>submenu2</span>
                    </a>
                </li>
                
            </ul>
        </li>

     <li >
            <a  data-bs-target="#econ-nav" data-bs- 
                 toggle="collapse" href="#">
                <i ></i><span>Expenses</span><i 
                     ></i>
            </a>
       <ul id="econ-nav"  data-bs-parent="#sidebar-nav">
                                      
                <li>
                    <a  href="submeni1.html">
                        <i ></i><span>SubMenu1</span>
                    </a>
                </li>
                <li>
                    <a  href="submenu2.html">
                        <i ></i><span>submenu2</span>
                    </a>
                </li>
                
            </ul>
        </li>

and js

 $(document).ready(function () {
        $('.sub').click(function () {

            $(this).parent('nav-content collapse > ul').addClass('show');

         
        });
    });

CodePudding user response:

When you call .parent() on an element it gives you the immediate parent of that specific element.

In your case it will be the <li> element above the anchor elements. If you want to access <ul> element, you will have to get the parent of the <li> element.

You can do this by calling .parent() again on the element returned by .parent().

$(this).parent().parent().addClass('show');

CodePudding user response:

To find a specific element in jquery if they have many levels use

$(target_element).closest() to find parent level or
$(target_element).find() to find children level.

Ref: https://api.jquery.com/closest/
Ref: https://api.jquery.com/find/

Hope this might help you.

  • Related