1

I am new in jQuery ,I am trying to get the value of href attribute when the user clicks on a link but I am getting same values for href attributes. here is my html code

<div class="container">
    <ul>
        <li><a href="#1" >Sign In</a>
        </li>
        <li><a href="#2">Brand</a>
        </li>
        <li><a href="#3">Distributor Brand</a>
        </li>
        <li class="language"> <a href="#4">English</a>

            <ul id="language-select">
                <li><a href="#5">Spanish</a>
                </li>
                <li><a href="#6">French</a>
                </li>
                <li><a href="#">German</a>
                </li>
            </ul>
        </li>
    </ul>
</div>

and js

$(document).ready(function(){    
    $("a").click(function(){            
        var value=$(".container").find("a").attr("href");            
        alert("hello------>  "+value);
    });
});

Here's the fiddle http://jsfiddle.net/suraj0750/rmbvo9oh/1/

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • 4
    you need `var value=$(this).attr("href");` – Arun P Johny Sep 04 '14 at 10:50
  • down voting makes no sence – Alex Sep 04 '14 at 10:55
  • Why is this Question voted down? It is clearly formulated and even has a fiddle... – nothing9 Sep 04 '14 at 10:56
  • might be because a simple search for [jquery get clicked elements href](https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=active&q=jquery%20get%20clicked%20elements%20href) would have given the answer - anyway the downvote was not from me – Arun P Johny Sep 04 '14 at 11:01

2 Answers2

7

try this :-

 var  value=$(this).attr("href");

Demo

Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
3

In JavaScript, when you bind an event to an element, the this variable is being available (of course depending on the element and event). So, when you click an element and bind a function, within that function scope the clicked element is referenced as this. Writing $(this) you make a jQuery object out of it:

$(document).ready(function(){

  $("a").click(function(){

    var value = $(this).attr("href");

    alert("hello------>  " + value);
  });


});
Alex
  • 9,911
  • 5
  • 33
  • 52