Search code examples
jqueryfindhrefdocumentattr

jQuery - How can I find the same href attr on document?


edit: delete dev-link!

At the bottom you'll see a sitemap navigation. If I hover a navpoint at bottom, it also should be highlight (addClass) the same Navpoint at my top navigation. You'll see the Links are the same. For exp. there's only six ...

I write the "href attr." on mouseHover into my variable "aHref":

$(".psSitemap a").hover(
    function() {
        var aHref = $( this ).attr('href');
        console.log(aHref);

        // addClass 'active' to the comparable Top Navigation Item href is the same!
    }, function() {
        // removeClass 'active' at Top Navigation
    }
);

But how can I also "find" the comparable ahref.attr at my document?

Thanks for your help.


Solution

  • For var aHref = $( this ).attr('href'); the matching top navigation link is

    $(".full-size a[href='" + aHref +  "']")  
    

    For the question if it's possible to write the function to change the matching topnav link on hovering sitemap links in an easier way - it can be reduced by using toggleClass() instead of adding and removing the class in two separate functions and not declaring any variables (though this can be useful for readability, it's not needed) :

    $(document).ready(function () {
        $(".psSitemap a").hover(
        function () {
            $(".full-size a[href='" + $(this).attr('href') + "']").toggleClass('comparable');
        });
    });
    ul {
      list-style-type: none;
    }
    li {
      display: inline;
    }
    a {
      color: #000;
    }
    .comparable {
      background-color: blue;
      color: #fff;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <ul class="full-size">
      <li><a href="first.html">First</a>
    
      </li>
      <li><a href="second.html">Second</a>
    
      </li>
      <li><a href="third.html">Third</a>
    
      </li>
    </ul>
    <ul class="psSitemap">
      <li><a href="first.html">First</a>
    
      </li>
      <li><a href="second.html">Second</a>
    
      </li>
      <li><a href="third.html">Third</a>
    
      </li>
    </ul>