Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find specific element in jQuery's .each function and do something with it

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?

like image 751
Max Avatar asked Jan 26 '26 13:01

Max


1 Answers

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>
like image 71
Nickz Avatar answered Jan 28 '26 03:01

Nickz