JavaScript中innerHTML, innerText和value的区别是什么?
当前回答
innerText和innerHTML都返回HTML元素的内部部分。
innerText和innerHTML之间唯一的区别是:innerText返回HTML元素(整个代码)作为字符串并在屏幕上显示HTML元素(作为HTML代码),而innerHTML只返回HTML元素的文本内容。
请看下面的例子以更好地理解。运行下面的代码。
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.'; . getelementbyid(“innertext的实现)。innerText = ourstring; . getelementbyid(“innerhtml”)。innerHTML = ourstring; . name { 颜色:红色; } <p><b>下面的内部文本。</b></p> < p id = " innertext”实现> < / p > < br > <p><b>下面的内部html。它将字符串呈现到元素中,并将其视为html文档的一部分 < p id = " innerhtml " > < / p >
其他回答
1)内部网页
设置标记内的所有HTML内容 返回标记内的所有HTML内容 包括样式+空白
2) innerText
设置标记内的所有内容(使用标记对应的换行符) 返回标签内的所有HTML内容(带有标签对应的换行符) 忽略标签(只显示文本) 忽略样式+空白 如果我们有style:"visibility:hidden;"内标签 |_ innerText包含样式->隐藏内容
(3) textContent
设置标签内的所有内容(没有标签对应的换行符) 返回标签内的所有内容(没有标签对应的换行符) 包括空格 如果我们有style:"visibility:hidden;"内标签 |_ textContent忽略样式->显示内容 textContent具有更好的性能,因为它的值不会解析为HTML。
Innerhtml将应用HTML代码
内文将把内容作为文本,所以如果你有HTML标签,它将显示为文本
就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富文本,并且不会自动对文本进行编码和解码。