JavaScript中innerHTML, innerText和value的区别是什么?
当前回答
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属性对内容进行html编码,将<p>转换为<p>等等。如果你想插入HTML标签,你需要使用InnerHTML。
就mutation观察者而言,设置innerHTML会生成一个childList突变,因为浏览器会删除节点,然后添加一个带有innerHTML值的新节点。
如果设置innerText,则会生成characterData突变。
innerText属性设置或返回指定节点及其所有后代的纯文本文本内容,而innerHTML属性获取和设置元素中的纯文本或HTML内容。与innerText不同,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。
InnerText将仅以纯文本形式返回页面的文本值,其中每个元素在换行符上,而innerHTML将返回body标记内所有内容的HTML内容,而childNodes将返回一个节点列表,顾名思义。
不过,与innerText不同的是,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。换句话说,innerText检索并将标记的内容设置为纯文本,而innerHTML检索并设置为HTML格式的内容。
推荐文章
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?