gotqn
gotqn

Reputation: 43636

jQuery get the text of all elements in a page

I want to get the text of all elements. I am using this code here:

$('*').filter(function()
{
    if(($(this).text().lenght>0)&&($(this).text().lenght<100))
    {
        return true;
    }
    else
    {
        return false;
    }
}).each(function()
{
    console.log($(this).text());
});

I have try to show only short text because .text() sometime returns html code but it is not working at all.

Upvotes: 3

Views: 19495

Answers (4)

ninja
ninja

Reputation: 2263

cant check if this works atm, but something like this should be what you are after, might need some modifications to filter out scripts and stuff.

$('body').children().each(function(index) {
     yourarray[index] = $(this).text();
});

EDIT: Tried it out and realised it only takes the first children, not grandchildren and also includes alot of whitespace and stuff aswell, I don't have time to code the entire function for you, but here is a good start atleast. .find('*') fetches all elements inside the document.

$("body").find('*').each(function (index) {
    //checks that the text isnt empty, no need to store that.
    if ($(this).text() != '') {
        //stores the elements text inside a temp variable, 
        //trims it from whitespaces and console.logs the results.
        temp = $(this).text();
        yourarray[index] = $.trim(temp);
        console.log(index+': '+yourarray[index]);
    }
});

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328624

It's much more simple: $('body').text() gives you the whole text on the page.

If you need to iterate over all the text nodes, see here: How do I select text nodes with jQuery?

Upvotes: 12

camden_kid
camden_kid

Reputation: 12813

Maybe this:

$("body").find().each(function () {
    if ($(this).text != undefined) {
        ...
    }
}

Upvotes: 0

Dhaval
Dhaval

Reputation: 26

There is spelling mistake of length it should be

$('*').filter(function()
{
    if(($(this).text().length>0)&&($(this).text().length<100))
    {
        return true;
    }
    else
    {
        return false;
    }
}).each(function()
{
    console.log($(this).text());
});

Upvotes: 1

Related Questions