Javascript DOM HTML Node textContent Property with innerText and innerHTML

Introduction

This example demonstrates some of the differences between innerText, innerHTML and textContent:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p id="demo">   This element has extra spacing   and contains <span>a span element</span>.</p>

<button onclick="getInnerText()">Get innerText</button>
<button onclick="getHTML()">Get innerHTML</button>
<button onclick="getTextContent()">Get textContent</button>

<p id="demo1"></p>

<script>
function getInnerText() {//from w ww  .  j a v  a  2  s .  c  o  m
  document.getElementById("demo1").innerText = document.getElementById("demo").innerText;
}

function getHTML() {
  document.getElementById("demo1").innerText = document.getElementById("demo").innerHTML;
}

function getTextContent() {
  document.getElementById("demo1").innerText = document.getElementById("demo").textContent;
}
</script>

</body>
</html>

The innerText property returns just the text, without spacing and inner element tags.

The innerHTML property returns the text, including all spacing and inner element tags.

The textContent property returns the text with spacing, but without inner element tags.




PreviousNext

Related