JavaScript中innerHTML, innerText和value的区别是什么?


当前回答

要添加到列表中,innerText将保留您的文本转换,innerHTML习惯。

其他回答

就mutation观察者而言,设置innerHTML会生成一个childList突变,因为浏览器会删除节点,然后添加一个带有innerHTML值的新节点。

如果设置innerText,则会生成characterData突变。

innerText属性返回html元素的实际文本值,而innerHTML返回html内容。在下面的例子:

var element = document.getElementById('hello'); element.innerText = '<strong> hello world </strong>'; console.log('The innerText property will not parse the html tags as html tags but as normal text:\n' + element.innerText); console.log('The innerHTML element property will encode the html tags found inside the text of the element:\n' + element.innerHTML); element.innerHTML = '<strong> hello world </strong>'; console.log('The <strong> tag we put above has been parsed using the innerHTML property so the .innerText will not show them \n ' + element.innerText); console.log(element.innerHTML); <p id="hello"> Hello world </p>

innerText属性设置或返回指定节点及其所有后代的纯文本文本内容,而innerHTML属性获取和设置元素中的纯文本或HTML内容。与innerText不同,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。

InnerText将仅以纯文本形式返回页面的文本值,其中每个元素在换行符上,而innerHTML将返回body标记内所有内容的HTML内容,而childNodes将返回一个节点列表,顾名思义。

要添加到列表中,innerText将保留您的文本转换,innerHTML习惯。