问题
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.
回答1:
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?
回答2:
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());
});
回答3:
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]);
}
});
回答4:
Maybe this:
$("body").find().each(function () {
if ($(this).text != undefined) {
...
}
}
来源:https://stackoverflow.com/questions/9533860/jquery-get-the-text-of-all-elements-in-a-page