What is the difference between innerHTML
, innerText
and childNodes[].value
in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
In simple words:
innerText
will show the value as is and ignores anyHTML
formatting which may be included.innerHTML
will show the value and apply anyHTML
formatting.InnerText
will only return the text value of the page with each element on a newline in plain text, whileinnerHTML
will return the HTML content of everything inside thebody
tag, andchildNodes
will return a list of nodes, as the name suggests.The examples below refer to the following HTML snippet:
The node will be referenced by the following JavaScript:
element.innerHTML
Sets or gets the HTML syntax describing the element's descendants
This is part of the W3C's DOM Parsing and Serialization Specification. Note it's a property of
Element
objects.node.innerText
Sets or gets the text between the start and end tags of the object
innerText
was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016,innerText
was adopted by the WHATWG and was added to Firefox in v45.innerText
gives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means:innerText
appliestext-transform
andwhite-space
rulesinnerText
trims white space between lines and adds line breaks between itemsinnerText
will not return text for invisible itemsinnerText
will returntextContent
for elements that are never rendered like<style />
and `Node
elementsnode.textContent
Gets or sets the text content of a node and its descendants.
While this is a W3C standard, it is not supported by IE < 9.
Node
elementsnode.value
This one depends on the element that you've targeted. For the above example,
x
returns an HTMLDivElement object, which does not have avalue
property defined.Input tags (
<input />
), for example, do define avalue
property, which refers to the "current value in the control".From the docs:
Sample Script
Here's an example which shows the output for the HTML presented above:
In terms of
MutationObservers
, settinginnerHTML
generates achildList
mutation due to the browsers removing the node and then adding a new node with the value ofinnerHTML
.If you set
innerText
, acharacterData
mutation is generated.To further refine it and retrieve the value Alec for example, use another .childNodes[1]
InnerText
property html-encodes the content, turning<p>
to<p>
, etc. If you want to insert HTML tags you need to useInnerHTML
.