Get the text within an element—including alt text—using jQuery

When working on the butterfly lightbox I needed a way to grab the text with a link including the alt text from any images within.

I couldn’t find any existing approaches, so I put together this small plugin to do the job. I thought I should post it here before I forget, or in case anyone else might find it useful too.

Example

If you had the following html:

<a id="smiley" href="">The symbol for happiness is <img src="smiley.png" alt="a smiley face" /></a>

You could grab the accessible text using the jQuery plugin like this:

$('#smiley').accessibleText();

Which would return the text ‘The symbol for happiness is a smiley face‘.

Plugin code

/**
 * jQuery plugin that returns the text nodes within the target element, combined/concatenated 
 * with any alt text or input values.
 */
$.fn.accessibleText = function() {
	if (this.is('img')) {
		return this.attr( 'alt' );
	} else if (this.is('input')) {
		return this.attr( 'value' );
	} else {
		return $.map( this.contents(), function( domElement ) {
			if ( domElement.nodeType === 3 ) {
				return domElement.data;
			} else if ( domElement.nodeType === 1 ) {
				var $element = $( domElement );
				if ( $element.is( 'img, imput' ) || $element.find( 'img[alt], input[value]' ).length > 0 ) {
					return $element.accessibleText();
				} else {
					return $element.text();
				}
			}
		}).join( '' );
	}
};

Let me know if you found this useful, or if you know of a better solution!

Edit: Much improved version above, thanks to Ben!
Edit again: I have updated it again to support input elements, and support using the plugin on inputs and imgs directly (this should really go on github).
Final edit: Here it is, accessibleText on github.

Posted in

Leave a reply