javascript 如何获取html页面中所有p和h标签的值,不包括所有其他标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11625048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get the value of all p and h tags in a html page excluding all other tags
提问by cavallo
I am trying to load a HTML page into my app. I want to show only the content of the HTML page.
please help me with a javascript function where I can loop through all the ptags and get the content of the <p>
tags to display in a TextViewas string.
我正在尝试将 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>
回答by Dominik Kirschenhofer
If you do not want to use jQuery just do:
如果您不想使用 jQuery,请执行以下操作:
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
alert(paragraphs[i].innerHTML);
}
回答by kr00lix
For looking by separated selectors you can write them by comma in jQuery
要通过分隔的选择器查找,您可以在 jQuery 中用逗号编写它们
$("p, :header").each(function(index, element){
console.info($(element).html());
})
回答by mr.b
Here one line jquery script will do. $("body p").text()
这里一行 jquery 脚本就可以了。 $("body p").text()
If you want to get per <p>
line, you can also do it like this
如果你想得到每<p>
行,你也可以这样做
$("body").children("p").each(function(e,v){
alert($(v).text());
});?