如何获取html页面中所有p和h标记的值,不包括所有其他标记

how to get the value of all p and h tags in a html page excluding all other tags

本文关键字:何获取 其他 不包括 html 获取      更新时间:2024-02-01

我正在尝试将HTML页面加载到我的应用程序中。我只想显示HTML页面的内容。请帮助我使用javascript函数,在该函数中,我可以循环浏览所有p标记,并获取<p>标记的内容,以字符串形式显示在TextView中。

<html><body>" +
        "<h1>First</h1><p>text text text</p>" +
        "<h1>Second</h1>more text" +
         <p>text text text</p>
           <p>text text text</p>
          <p>text text text</p>
        "</body></html>

如果您不想使用jQuery,只需执行:

var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
    alert(paragraphs[i].innerHTML);
}

对于通过分隔的选择器进行查找,您可以在jQuery 中用逗号书写它们

$("p, :header").each(function(index, element){ 
   console.info($(element).html());  
})

这里只需一行jquery脚本即可。$("body p").text()

如果你想得到每条<p>线,你也可以像这个一样

$("body").children("p").each(function(e,v){
    alert($(v).text());
});​