How To Remove/Replace Text From An ALT Tag Using jQuery

This post discusses on how to remove/replace text from an alt tag using jQuery. The alt tag is one of the attributes of an HTML image tag, and specifies the text to be used as an alternative to an image which doesn’t render in the web page for some reason.

Let’s suppose we have a snippet of code which includes a couple of images, each one reading as below.

<img src="image1.jpg" alt="<font color="#000000">Web Project: textxxxtext </font>" />

We want to remove the HTML from the alt tags. So, each alt tag will be reading as follows:

alt="Web Project: textxxxtext"

A solution is described below, and its demo can be found in the home page of this site; just hover each image of the slider located on top of the page.

Resources

  1. Dependency. The jQuery Library is included in the head of the HTML document.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

Utilities

  1. .each( function )
  2. .attr( attributeName )
  3. .slice( start [, end ] )
  4. .prop( propertyName )

Description

We used .each() to loop through each image starting at index 0. Then, the code finds the string value of each alt tag using .attr(), and removes the first 22 characters and the last 7 characters of the string using .slice(). We set the new value of the alt tag by replacing the old string (str) with the new string (strResult) using .prop(). We wrap this code inside a conditional statement which only runs if "body.page-id-122" exists in the web page.

JavaScript

<script>
if(jQuery('body.page-id-122').length > 0){

         jQuery('.featured-slider img').each(function(){

            var str = jQuery(this).attr('alt'),
            strResult = str.slice(22).slice(0,-7);

            jQuery(this).prop('alt',strResult);

         });

     }

About the Author

Maria C. Lima

Maria C. Lima has spent the past 10 years studying web development and becoming a sought-after independent web designer & developer in New York City. She now runs MCL Interactive, her own NYC design and technology firm, where she prides herself in providing creative web solutions for savvy entrepreneurs. She helps bring their vision to life in a beautiful and functional web presence. Her goal is to take care of all the techy stuff so that they can do what they love and work on growing their businesses. You can find her on Twitter (@mclinteractive) or on Facebook (Facebook.com/mclinteractive). Read more

Related posts

You might be interested in the following posts: