Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of alt attribute of img tag? [duplicate]

Tags:

jquery

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??

like image 856
Vivek Pipaliya Avatar asked Dec 31 '13 18:12

Vivek Pipaliya


People also ask

What is the value of alt attribute of IMG tag?

The required alt attribute specifies an alternate text for an image, if the image cannot be displayed. The alt attribute provides alternative information for an image if a user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).

How do I find the alt attribute of an image?

Chrome™ browser: point to the image with your mouse, right-click and choose Inspect from the quick menu (or use Ctrl-Shift-I on keyboard). A new pane will open at the right of your screen with the HTML code highlighted for that element. You can then view the alt text and other attributes for the image.

Can you have duplicate alt tags?

So yes, three images can all have the same alt text, but only if all three images are identical. If the images aren't identical, the alt texts should include a description of their differences.

What is the correct way to specify alt attribute with IMG tag?

The <img> alt attribute is used to specify the alternate text for an image. It is useful when the image not displayed. It is used to give alternative information for an image. Attribute Values: It contains single value text which specifies the alternative text for an image.


1 Answers

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/

like image 163
Felix Avatar answered Sep 18 '22 11:09

Felix