jQuery获取页面中所有元素的文本

时间:2012-03-02 13:09:59

标签: jquery text elements

我想获得所有元素的文本。我在这里使用这段代码:

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

我尝试只显示短文本,因为.text()有时会返回html代码,但它根本不起作用。

4 个答案:

答案 0 :(得分:12)

更简单:$('body').text()为您提供页面上的全文。

如果您需要遍历所有文本节点,请参阅此处:How do I select text nodes with jQuery?

答案 1 :(得分:1)

length拼写错误应该是

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

答案 2 :(得分:1)

无法检查这是否有效,但是这样的事情应该是你所追求的,可能需要一些修改来过滤掉脚本和东西。

$('body').children().each(function(index) {
     yourarray[index] = $(this).text();
});
编辑:尝试了,并意识到它只需要第一个孩子,而不是孙子,还包括很多空白和东西,我没有时间为你编写整个功能,但这是一个良好的开端至少。 .find('*')获取文档中的所有元素。

$("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]);
    }
});

答案 3 :(得分:0)

也许这个:

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