首页 > 解决方案 > JS - 如何获取outerHTML textContent的字符串?

问题描述

JavaScript 中的问题 - 我使用 tagName 定义了一个元素,我想获取它的完整定义的字符串(如“

let elem = elementsArr[i].outerHTML.textContent;

它返回我未定义。我需要一些帮助:)

只想知道为什么我的代码不起作用

标签: javascriptouterhtml

解决方案


只想知道为什么我的代码不起作用

因为.outerHTML没有方法.textContent,所以返回undefined

如果要获取元素的内容,可以使用.innerHTML.

或者,如果您只想要文本,您可以.textContent在元素上使用。

见例子:

d = document.getElementById("d");
console.log(d.outerHTML);
console.log(d.innerHTML);
console.log(d.textContent); 
<div id="d"><p>Content</p><p>Further Elaborated</p></div>


推荐阅读