Forces / usetheforces-accessibleText

jquery plugin to get the text equivalent of an element (includes alt text)
http://irama.org/news/2011/08/20/get-the-text-within-an-elementincluding-alt-textusing-jquery/
2 stars 0 forks source link

possibly simpler implementation? #1

Open bboyle opened 12 years ago

bboyle commented 12 years ago

Might be simpler to clone the element, then manipulate the cloned tree and simply return .text() at the end. No recursion, no lengthy string concatenation. Need to test which algorithm performs faster (try http://jsperf.com/)

        var clone = this.clone();

        clone.find( 'script, noscript' ).remove();
        clone.find( 'img' ).map(function() {
            return this.alt;
        });
        clone.find( 'input' ).map(function() {
            return this.value;
        });

        return clone.text();
rajkundu commented 4 years ago

I'm not sure why your code verbatim wasn't working for me, so I slightly modified the syntax:

function textAndImages()
{
    var clone = $($("#myElementID")[0]).clone();
    var imgs = clone.find("img");
    for(var i = 0; i < imgs.length; i++)
    {
      $(imgs[i]).replaceWith($(imgs[i]).attr("alt"));
    }
    return clone.text();
}

(Note that all my code does is replace images with their alt text; it doesn't do anything with script, noscript, or input tags)