I have the following html:
<!-- MainMenu -->
<ul class="main-menu">
<li><a href="About/xxxxx">About</a></li>
<li><a href="Services/xxxxx">Services</a></li>
<li><a href="Portfolio/xxxxx">Portfolio</a></li>
</ul>
<!-- /MainMenu -->
<!-- MainMenu -->
<ul class="sub-menu">
<li><a href="xxxxx/subpage1.html">About Main</a></li>
<li><a href="xxxxx/subpage2.html">About Main</a></li>
<li><a href="xxxxx/subpage3.html">About Main</a></li>
</ul>
<!-- /MainMenu -->
And following jQuery, which already cut URL into needed to matching bits.
$(document).ready(function() {
urlParts = "www.website.com/About/subpage1.html".split("/")
var MainMenu = urlParts[1]+"/"; // mainmenu e.g About/XXXX
var SubMenu = urlParts[2]; //submenu e.g XXXX/subpage1.html
// Find matched to var = MainMenu within main-menu > li > a
// Find matched to var = SubMenu within sub-menu > li > a
});
What I want to do:
- Find matched to var = MainMenu within main-menu > li > a and addClass('active') to matched 'a'
- Find matched to var = SubMenu within sub-menu > li > a and addClass('active') to matched 'a'
So how can run through those menus looking for matches to those var?
You can assign ids or classes to each element and go one by one, or you can use
.each
.For instance:
You can use the
[name^="..."]
and[name$="..."]
selectors to match attributes that start and end with specific strings:Demo: http://jsfiddle.net/gWDm8/127/
Use the attribute selector.
http://api.jquery.com/attribute-equals-selector/
A simple but probably inaccurate solution is the usage of the
:contains
pseudo selector:That will add the class
active
to the parentli node
which contains ananchor
, which contains the string. More accurate is an exact matching:http://jsfiddle.net/MKH3Y/