Home >Web Front-end >JS Tutorial >Some problem analysis of innerText and innerHTML_javascript skills

Some problem analysis of innerText and innerHTML_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 18:52:52919browse

The innerText attribute is used to modify the text between the start tag and the end tag. For example, suppose you have an empty

element and want to turn it into
New text for the div.
. When implementing it with DOM, do this:
oDiv.appendChild(document.createTextNode("New text for the div."));
This code is not difficult to read, but it is very verbose. If using innerText, just do this:
oDiv.innerText = "New text for the div.";
Using innerText, the code is more concise and easier to understand. In addition, innerText will automatically HTML-encode the less than sign, greater than sign, quotation marks and & symbols, so there is no need to be careful about special characters:
oDiv.innerText = "New text for the
.";
The execution result of this line of code is
New text for the
.
. But how do we have to include HTML tags in elements? This is the problem innerHTML aims to solve.
Using the innerHTML feature, you can directly assign HTML strings to elements without considering the use of DOM methods to create elements. For example, suppose an empty
is to become
HelloWorld
. To use DOM, use the following code:
var oStrong = document.createElement("strong');
oStrong.appendChild(document.createTextNode("hello"));
var oEm = document.createElement ("em");
oEm.appendChild(document.createTextNode("World"));
oDiv.appendChild(oStrong);
oDiv.appendChild(document.createTextNode(""));
oDiv.appendChild(oEm);
With innerHTML, the code becomes:
oDiv.innerHTML = "HelloWorld";
Seven lines The code becomes one line at a time, this is the power of innerHML!
You can also use innerText and innerHTML to get the content of the element. If the element only contains text, innerText and innerHTML return the same value. However, if it contains both text and innerHTML. For other elements, innerText will only return the representation of the text, while innerHTML will return the HTML code of all elements and text. The table below lists the different values ​​returned by innerText and innerHTML based on the specific code.
code innerText innerHTML

Hello world
代码 innerText innerHTML
Hello world
"Hello world" "Hello world"
Helloworld
"Hello world" "Helloworld"
"" ""
"Hello world" "Hello world"

Helloworld
"Hello world" "Helloworld"
"" ""
, by assigning innerText to itself, indicating that from Removes all HTML tags from the specified element. oDiv.innerText = oDiv.innerText;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn