Question

I want to find all the href containing current url even if the whole href is longer. E.g.
Current url: www.example.com/portfolio/
a href url: www.example.com/portfolio/#28

What I want to do is to add class to all <a>'s containing current url path (even if they are longer). I used something like this:

<script type="text/javascript">
var nav = $(location).attr('href');
if (nav) { 
jQuery('a[href$="' + nav + '"]').parent().addClass('current');
}
</script>   

But the code add the class only to 's containg the exact same path like current url.

Was it helpful?

Solution

Use the starts with selector:

<script type="text/javascript">
var nav = $(location).attr('href');
if (nav) { 
jQuery('a[href^="' + nav + '"]').parent().addClass('current');
}
</script> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top