innerText、innerHTML、textContent的区别

1,015 阅读1分钟

innerText

innerText 属性只返回文本,不包含段落外空格和内部元素标签。

<body>
<p id="para">    This is   a  <span>test</span> paragraph.    </p>
</body>
<script>
    consoel.log(document.getElementById('para').innerText); 
    // "This is a test paragraph."
</script>

innerHTML

innerHTML 属性返回文本,包含所有空格和内部元素标签。

<body>
<p id="para">    This is   a  <span>test</span> paragraph.    </p>
</body>
<script>
    consoel.log(document.getElementById('para').innerText); 
    // "    This is   a  <span>test</span> paragraph.    "
</script>

textContent

textContent 属性返回带空格的文本,但是不包含内部元素标签。

<body>
<p id="para">    This is   a  <span>test</span> paragraph.    </p>
</body>
<script>
    consoel.log(document.getElementById('para').innerText); 
    // "    This is   a  test paragraph.    "
</script>