Search code examples
javascriptjquerycssdom-traversal

Retrieve all italic text snipets on a page in jQuery and/or javascript


I'm looking to run a script on a page that puts each piece of text that is italicized into an array.

As I understand jQuery .find() you can't get items by attributes, am I right?


Solution

    • You should get familiar with the filter() method which is a great jQuery feature. You can define a filter function you can use to reduce the elements in your jQuery collection to the ones that fit your needs.

    • You also need to use .map() which is another super-handy method that can help you create lists from your jQuery collections defined by a function you write. Using .get() you can create a plain Javascript array from this jQuery list object.

    This is a basic version that will collect you the text content of elements that have font-style: italic applied to them:

    var arr = 
        $('*') /*look at all elements*/
            .filter(function () { /*filter these elements*/
                return $(this).css('font-style') == 'italic'; /*only keep the italic*/
            })
            .map(function () { /*create a new object using these elements*/
                return $(this).text(); /*store the text of each selected element*/
            })
            .get(); /*convert this to an array*/
    

    jsFiddle Demo