views:

36

answers:

6

Hi,
Whats wrong with my code? Why does .atrr() show empty?
Thanks

$(document).ready(function(){
   $('#push').click(function(){
      alert($('#push2').attr('href').val);
   }); 
});  

HTML:

<div id="push">PUSH</div>
<a id="push2" href="http://www.google.com"&gt;PUSH Google</a>
+2  A: 

I think you don't need .val after $('#push2').attr('href'). attr function already returns string.

Nikita Rybak
fast, fiver replies in one minute :)
Nikita Rybak
A: 

Im not sure you need the .val after the attr. function? Try that and see what you get.

Noctine
+7  A: 

.attr() already returns a string, so just use it directly (without the .val):

$(document).ready(function(){
    $('#push').click(function(){
        alert($('#push2').attr('href'));
    }); 
}); 

You can test it here. The reason you see undefined currently is because the .val property of a string object is undefined :)

Nick Craver
A: 

try

alert($('#push2').attr('href').text());

FutureKode
A: 

Your using the same id for the div and for the anchor. Ids must be unique. Jquery pulls the first element which is the div and yes that div doesn't have an href Just use $('#push2').attr('href');

andrei
+1  A: 
$('#push2').attr('href')
Detect