Here is my markup:
<ul class="tab1">
<li><a href="http://site.com/some.html?param=1"></li>
<li><a href="http://site.com/some.html?param=2"></li>
<li><a href="http://site.com/some.html?param=3"></li>
...
</ul>
I'm trying to compare if the current window.location matches any of the list anchors, and if true, then I'd like to do something like addClass('active').
My code for checking the current location of the browser and getting the href parameters from the list elements:
// get current url parameter
var getBrowserUrl = document.URL.split('?')[1];
// get parameters of all the <li> anchors
jQuery('.tab1 a').each(function(){
var getElementUrl = jQuery(this).attr('href').split('?')[1];
if (getBrowserUrl == getElementUrl ) {
jQuery(this).addClass('active');
}
});
The jQuery(this) bit obviously isn't working, since 'this' will refer to all of the list elements.
How can i specify the matching list element?
I've tested your code and made a few modifications try the following:
<ul class="tab1">
<li><a href="http://site.com/some.html?param=1"/></li>
<li><a href="http://site.com/some.html?param=2"/></li>
<li><a href="http://site.com/some.html?param=3" /></li>
</ul>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
// get current url parameter
var getBrowserUrl = document.URL.split('?')[1];
// get parameters of all the <li> anchors
$('.tab1 a').each(function () {
var getElementUrl = $(this).attr('href').split('?')[1];
if (getBrowserUrl == getElementUrl) {
$(this).addClass('active');
}
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With