DOM/Javascript:在标记后获取文本

新手上路,请多包涵

如何获取 html 文档中标记后的文本“那里”:

 <p><a>hello</a>there</p>

我看到有一种方法可以用 xpath 做到这一点:

从下一个标签获取文本

但我没有使用 xpath,我希望不必为此开始。我意识到我可以获得 p 标签内的所有文本,但我只想获得“那里”的文本,以及它与 p 和 a 标签的关系。它似乎不是任何人的孩子或兄弟姐妹。 (你可以假设我可以获得任何其他元素/节点,因此它可以与那些元素/节点相关。)每个 DOM 教程似乎都忽略了文本可以出现在标签之外的事实。

谢谢。

原文由 user984003 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 239
2 个回答

您可以使用多种方式获取标签和文本

 let p = document.querySelector('p'); // first p on the page
console.log(p.lastChild.textContent)

let ps = document.querySelectorAll('p'); // all p on the page
console.log(ps[0].lastChild.textContent)

// using tagName
p = document.getElementsByTagName('p')[0];
console.log(p.childNodes[1].textContent)
 <p><a>hello</a>there</p>

原文由 mplungjan 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用这个 .. http://jsfiddle.net/2Dxy4/

这是你的 HTML——

 <p id="there">
   <a>hello</a>
   there
</p>​

在你的 JS

 alert(document.getElementById("there").lastChild.textContent)​

或者

alert(document.getElementById("there").childNodes[1].textContent)​

原文由 Vivek Chandra 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题