5

I cannot get the value of attribute alt of img tag

Following is for Getting the value of attribute alt of img tag

<html>
<head>
<script>

$('img').click(function () {
    var alt = $(this).attr("alt")
    alert(alt);
});

</script>
</head>

<img src="white.png" width="25px" height="25px" alt="1" id="star1" onmouseover="starOverOne()" onmouseout="starOutOne()"/>

Here Nothing displayed in alertbox..Can you help me??

Felix
  • 37,892
  • 8
  • 43
  • 55
Vivek Pipaliya
  • 488
  • 1
  • 7
  • 17
  • 5
    You can't bind event handlers to elements that don't yet exist. If the script is at the top, it runs before the `img` has loaded. – cookie monster Dec 31 '13 at 18:09
  • 1
    Wrap your code in `$(document).ready` – Jose Dec 31 '13 at 18:10
  • 1
    Also, you can do `this.alt;`. Much shorter and faster than using jQuery for that. – cookie monster Dec 31 '13 at 18:12
  • **Please (!)** read the [jQuery tutorial](http://learn.jquery.com/). [It explicitly states](http://learn.jquery.com/about-jquery/how-jquery-works/): *"To run code as soon as the document is ready to be manipulated, jQuery has a statement known as the [ready event](http://api.jquery.com/ready/) [...]"*. The purpose of the tutorial is exactly this, help newcomers to get started with jQuery. – Felix Kling Dec 31 '13 at 18:13
  • @FelixKling: You kidding? People don't read tutorials and docs anymore. They just ask someone for help now. Where have you been? ;-D – cookie monster Dec 31 '13 at 18:15

1 Answers1

7

Remember to wrap your code inside $(document).ready(function() {...}); and include your jQuery library. Try to follow this basic HTML structure:

<html>
<head>

</head>

<body>
<img src="white.png" width="25px" height="25px" alt="1" id="star1" onmouseover="starOverOne()" onmouseout="starOutOne()"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('img').click(function () {
        var alt = $(this).attr("alt")
        alert(alt);
    });
});
</script>
</body>
</html>

Demo: http://jsfiddle.net/aHRN7/

Felix
  • 37,892
  • 8
  • 43
  • 55