Set alt attribute to images dynamically using jquery

In this programming tutorial, we will learn how to set alt attribute to images dynamically using jquery. Once again i say, in jquery doing so is quite easy :). Let's have a look over how to do so.
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("img:not([alt])").each(function () {
		$(this).attr('alt', 'image here');
                //alert($(this).attr("src"));
            });
        }); 
        </script>

By using the jquery's built-in attr() function, the above mentioned code snippet will check each and every image in the body of your web page and assign alt attribute dynamically to those images in which alt attribute is missing. Right now i am assigning image here as a hard coded value of alt attribute, but you can assign the image name as a value of alt attribute as well, depends upon your requirement.

Note:- After applying the above mentioned code, please check the required change in source code by using firebug because if you check the source code by right clicking the web page then you will not find any change made by the above mentioned code, as jquery doesn't change the original html of the web page. I can understand most of you are well aware of firebug but those my brothers that don't know about firebug, definitely i will write a tutorial for them very soon.

So that's it. I hope you will find this tutorial very handy.

I love your feedback.

0 comments: