Exploring the Distinctions Between innerText, innerHTML, and value
Understanding the Differences
In JavaScript, the attributes innerText, innerHTML, and value provide different ways to interact with the HTML content of a web page. Each of these attributes has its own specific functionality and use cases.
innerHTML: HTML Representation
The innerHTML property reflects the HTML syntax describing the descendants of an element. It provides a representation of the HTML content within the element's opening and closing tags.
innerText: Rendered Text
The innerText property captures the rendered text within an element. It presents the content as it appears on the screen, taking into account applied styles and white-space rules. Specifically, innerText:
textContent: Raw Text
textContent retrieves the text content of a node and its descendants. Unlike innerText, it preserves whitespace and ignores any applied styles or display properties. This results in a more literal representation of the content.
value: Element-Specific Attribute
The value attribute primarily applies to form inputs, like text boxes and checkboxes. It represents the value currently stored in the control. Notably:
Example Script for Comparison
The following JavaScript script showcases the differences between these attributes:
var properties = ['innerHTML', 'innerText', 'textContent', 'value']; // Logs property as [propName]value[/propertyName] function logProperty(obj, property) { var value = obj[property]; console.log('[' + property + ']' + value + '[/' + property + ']'); } // Main log('=============== ' + properties.join(' ') + ' ==============='); for (var i = 0; i < properties.length; i++) { logProperty(document.getElementById('test'), properties[i]); }
When applied to the HTML snippet below, the script outputs the following in the console:
<div>
Output:
[innerHTML][ Warning: This element contains <code>code</code> and <strong>strong language</strong>. ][/innerHTML] [innerText]Warning: This element contains code and strong language.[/innerText] [textContent] Warning: This element contains <code>code</code> and <strong>strong language</strong>. [/textContent] [value]null[/value]
This output demonstrates how innerText returns the rendered text, innerHTML the complete HTML representation, textContent the raw text including whitespace, and value (since test is a div element) is null.
The above is the detailed content of What are the key differences between `innerText`, `innerHTML`, `textContent`, and `value` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!