JavaScript中innerHTML, innerText和value的区别是什么?
当前回答
innerText属性设置或返回指定节点及其所有后代的纯文本文本内容,而innerHTML属性获取和设置元素中的纯文本或HTML内容。与innerText不同,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。
其他回答
InnerText属性对内容进行html编码,将<p>转换为<p>等等。如果你想插入HTML标签,你需要使用InnerHTML。
不过,与innerText不同的是,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。换句话说,innerText检索并将标记的内容设置为纯文本,而innerHTML检索并设置为HTML格式的内容。
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 >
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>
Innerhtml将应用HTML代码
内文将把内容作为文本,所以如果你有HTML标签,它将显示为文本
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?