3

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.

gotqn
  • 42,737
  • 46
  • 157
  • 243

4 Answers4

12

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?

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Yes, but I need individual text elements. For example: div with text "hi", div with text "user", etc. I need to have an array with this element's text in the final. That's why i use $('*') – gotqn Mar 02 '12 at 13:17
  • See the link in my answer how to iterate over all text nodes in a document. It's much more complicated than you'd think. – Aaron Digulla Mar 02 '12 at 13:33
  • Thank you all for the answers. I have fixed my function and make it a little more complicated to do what I want. I will look through your link too. – gotqn Mar 02 '12 at 14:13
1

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());
});
Dhaval
  • 26
  • 1
  • 5
1

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]);
    }
});
ninja
  • 2,233
  • 1
  • 15
  • 15
0

Maybe this:

$("body").find().each(function () {
    if ($(this).text != undefined) {
        ...
    }
}
camden_kid
  • 12,591
  • 11
  • 52
  • 88