<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
justify;line-height:normal">
First Text
<span lang="EN-US" style="font-size:12.0pt;
font-family:"Times New Roman","serif"">
Second Text</span>
</p>
这是我的代码,如何获取段落标记内的内容。 [标签可能会更改为div或ul]。我需要javascript中的段落标记内的所有内容。
输出应为:
第一篇文字第二篇文字
抱歉,我是javascript的新手,搜索但无法找到相关问题的答案。感谢
答案 0 :(得分:2)
要获取标记的值,您可以使用选择器获取元素并使用innerHTML
来获取值。像这样:
<p>hi there</p>
console.log(document.getElementsByTagName('p')[0].innerHTML);
n.b。在上面的代码中按标签名称选择,因此它返回一个匹配元素数组
因此,在您的示例中,使用.innerHTML
为您提供P
标记内容,包括任何html标记等。
如果您只想要内容,可以使用.textContent
console.log(document.getElementsByTagName('p')[0].textContent);
不会为您提供内部html标记
n.b。还有innerText
方法,但这并不是浏览器支持的。
答案 1 :(得分:0)
答案 2 :(得分:0)
InnerText应该是一个很好的解决方案。
console.log(document.getElementsByTagName('p')[0].innerText);
<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
justify;line-height:normal">
First Text
<span lang="EN-US" style="font-size:12.0pt;
font-family:"Times New Roman","serif"">
Second Text</span>
</p>