Search code examples
javascriptjqueryhtmlhref

Find and disabled <a href>


I have weird structure and want to disabled first element inside li.expanded using a[href="/abc"]. I have parent and child have same href and title is different. How can I select parent only element?

Here the code:

<ul class="n-right m-menu__link-list" id="main-right-menu">
    <li class="first leaf"><a href="/xyz" title="xyz-parent">xyz-parent</a></li>
    <li class="leaf"><a href="/pqr" title="pqr">pqr</a></li>
    <li class="last expanded"><a href="/abc" title="abc">abc</a>  //want to find this element and apply treatment

      <ul class="n-right m-menu__link-list" id="main-right-menu">
        <li class="first leaf"><a href="/abc" title="abc1">abc</a></li>  //not this one
        <li class="last leaf"><a href="/mno" title="mno">mno</a></li>
    </ul>
    </li>
</ul>

What I have tried, the function is working. it's selecting both a[href="/abc"] parent and child. I want to find and select only parent one.

openabcInNav: function() {
    var navEl = $('#main-menu, #main-right-menu li.expanded').find('a[href="/abc"]:nth-child(1)');
    navEl.addClass('doNotClose');
    navEl.on('click mouseover', function(event) {         
        event.preventDefault();
        $('nav.global-nav').find('li.expanded').toggleClass('show');
    });
},  

Solution

  • You could use the :first selector that will return the first occurrence what it the parent :

    $('ul>li.expanded>a[href="/abc"]:first')
    

    $('ul>li.expanded>a[href="/abc"]:first').css('background-color', 'green');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul class="n-right m-menu__link-list" id="main-right-menu">
      <li class="first leaf"><a href="/xyz" title="xyz-parent">xyz-parent</a></li>
      <li class="leaf"><a href="/pqr" title="pqr">pqr</a></li>
      <li class="last expanded"><a href="/abc" title="abc">abc</a> //want to find this element and apply treatment
    
        <ul class="n-right m-menu__link-list" id="main-right-menu">
          <li class="first leaf"><a href="/abc" title="abc1">abc</a></li> //not this one
          <li class="last leaf"><a href="/mno" title="mno">mno</a></li>
        </ul>
      </li>
    </ul>