As you probably know, you can get and set the text inside a DOM Element using two properties: Node.textContent and Element.innerText.
At first glance, they seem to be doing exactly the same thing, but there are some subtle but important differences. Today, we’ll take a look at what they do, and how they differ and differ.
Cut the crap and look at the code.
In common
Take the following DOM element.
<p id="sandwich">I love a good tuna sandwich! </p>Copy the code
The Node.textContent and Element.innerText attributes both retrieve the text inside the # Sandwich Element.
let sandwich = document.querySelector('#sandwich');
// returns "I love a good tuna sandwich!"
let text1 = sandwich.textContent;
// also returns "I love a good tuna sandwich!"
let text2 = sandwich.innerText;
Copy the code
If there are other tags inside the element, they ignore them.
<p id="sandwich">I love a good <strong>tuna</strong> sandwich! </p>Copy the code
// returns "I love a good tuna sandwich!"
let textHTML1 = sandwich.textContent;
// also returns "I love a good tuna sandwich!"
let textHTML2 = sandwich.innerText;
Copy the code
In addition, both attributes can be used to set the internal text of an element.
// <p id="sandwich">Hello, world! </p> sandwich.textContent = 'Hello, world! '; // <p id="sandwich">Hello, world! And hi, Universe! </p> sandwich.innerText += ' And hi, Universe! ';Copy the code
The difference
They seem to do the same thing, so what’s the difference?
Node.textContent
Properties forallText content, including content inside elements that is not rendered to the page.-
Element.innerText
Only rendered text is returned, similar to portions of text that can be selected with the cursor and keyboard.
Let’s take an example.
<div class="greeting"> <style type="text/css"> p { color: rebeccapurple; } </style> <p hidden>This is not rendered.</p> <p>Hello world! </p> </div>Copy the code
let greeting = document.querySelector('.greeting'); /* return p {color: rebeccapurple; } This is not rendered. Hello world! */ let text1 = greeting.textContent; // Return "Hello world!" let text2 = greeting.innerText;Copy the code
Now we know the difference! Lie down to learn another knowledge ~
Pay attention to the public number 1024 translation station, every day a hair loss tips ~