The difference of innerHTML, innerText, value in JS

Posted by imarockstar on Mon, 06 Jan 2020 00:36:37 +0100

I. difference

innerHTML

Adding HTML code to the control is to set the HTML in an element. The tag is effective for text information.

innerTEXT

Print the plain text information between the labels, display the labels, the labels are invalid, and the lower version of Firefox does not support it.

value

Display all contents in double quotation marks, display label, invalid label.

Two. Examples

Example 1

1,innerHTML

<!doctype html>
    <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p id="demo">my first demo</p>
</body>
<script>
    document.getElementById("demo").innerHTML="<b>hello world</b>"
</script>
</html>

2,innerTEXT

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <p id="demo">my first demo</p>
</body>
<script>
    document.getElementById("demo").innerText="<h1>My First JavaScript</h1>";
</script>
</html>

 

3,value

<!doctype html>
    <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p id="demo">my first demo</p>
    <input id="input" type="text">
</body>
<script>
    document.getElementById("input").value="<b>hello</b>"
</script>
</html>

Example two

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<script>
function test1(){
    
    window.alert(document.getElementById("value").value);
}

function test2(){

    window.alert(document.getElementById("innerHTML").innerHTML);

}

function test3(){

    window.alert(document.getElementById("innerText").innerText);

}
</script>
</head>
<body id="innerHTML">
//Message content: < span id = "innerText" > message < / span > < br / >
<input type="text" id="value" /><br/>
<input type="button" onclick="test1()" value="value" /><br/>
<input type="button" onclick="test2()" value="innerHTML"/><br/>
<input type="button" onclick="test3()" value="innerText"/><br/>
</body>
</html>

Refresh page:

Click the corresponding button to see the displayed content:

value:

           

innerHTML:

                        

innertext:

               

Three. Conclusion

1.innerText is the text in the tag, and the input and output are strings;
2.innerHtml is the text in the < tag, input and output to the pure HTML code inside the DOM;
3.value is a unique attribute of form elements, and the input and output are strings;

 

 

Topics: Firefox Javascript Attribute