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

March 22, 2015 Maria C. Lima

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.

Resources

  1. Dependency. The jQuery Library is included in the head of the HTML document.
<script type="text/javascript" src="https://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.

jQuery

<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);

         });

     }

, , ,
Maria C. Lima

Maria C. Lima

Maria is an esteemed and celebrated independent web developer based in New York City. Her design and development work show tremendous passion and insight, which she brings to all of her clients and projects with love, professionalism, and an esteemed work ethic admired by all who partner with Maria.