I've been working with jQuery and tried to add a class to a parent element that was 3 steps up the DOM tree. I didn't get it to work with "parents('selector')" but with "parent().parent().parent()". Could anyone of you help me out and explain why this isn't working?
function activeNav() { var nav_list_content = $('.nav_list_content'); var nav_sub_list_content = $('.nav_sub_list_content'); var CountNavSubListElements = nav_sub_list_content.length; var CountNavListElements = nav_list_content.length; for(var c = 0; c<CountNavListElements; c++){ if(nav_list_content.eq(c).attr("href") == window.location.href){ nav_list_content.eq(c).addClass('active_nav_link'); break; } } for(var c = 0; c<CountNavSubListElements; c++){ if(nav_sub_list_content.eq(c).attr("href") == window.location.href){ nav_sub_list_content.eq(c).parent().parent().parent().addClass('active_nav_link'); /*Does work*/ nav_sub_list_content.eq(c).parents('.nav_list_content').addClass('active_nav_link'); /*Doesn't work*/ break; } } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav id="prime_nav"> <div id="mobile_menu_button"><a id="mobile_menu_button_content" class="attr">☰</a></div> <div id="nav_wrapper"> <img id="logo" src="Logo.png"> <ul id="nav_list" class="nos"> <li class="nav_list_element"><a href="http://127.0.0.1:50241/index.html" class="nav_list_content attr">Home</a></li><!-- --><li class="nav_list_element"><a href="#" class="nav_list_content attr">Page</a></li><!-- --><li class="nav_list_element"> <a href="#" class="nav_list_content attr">Page</a> <ul id="nav_sub_list"> <li class="nav_sub_list_element"><a href="http://127.0.0.1:50241/index.html" class="nav_sub_list_content attr">Page</a></li> <li class="nav_sub_list_element"><a href="#" class="nav_sub_list_content attr">Page</a></li> </ul> </li><!-- --><li class="nav_list_element"><a href="#" class="nav_list_content attr">Page</a></li><!-- --><li class="nav_list_element"><a href="#" class="nav_list_content attr">Page</a></li> </ul> </div> </nav> I'm sorry for so much code. But I appreciate your help.
partents()not witheq(c).closest(SELECTOR)