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属性设置或返回指定节点及其所有后代的纯文本文本内容,而innerHTML属性获取和设置元素中的纯文本或HTML内容。与innerText不同,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。
要添加到列表中,innerText将保留您的文本转换,innerHTML习惯。
var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);
要进一步细化它并检索值Alec(例如,使用另一个.childNodes[1])
var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);
InnerText属性对内容进行html编码,将<p>转换为<p>等等。如果你想插入HTML标签,你需要使用InnerHTML。
1)内部网页
设置标记内的所有HTML内容 返回标记内的所有HTML内容 包括样式+空白
2) innerText
设置标记内的所有内容(使用标记对应的换行符) 返回标签内的所有HTML内容(带有标签对应的换行符) 忽略标签(只显示文本) 忽略样式+空白 如果我们有style:"visibility:hidden;"内标签 |_ innerText包含样式->隐藏内容
(3) textContent
设置标签内的所有内容(没有标签对应的换行符) 返回标签内的所有内容(没有标签对应的换行符) 包括空格 如果我们有style:"visibility:hidden;"内标签 |_ textContent忽略样式->显示内容 textContent具有更好的性能,因为它的值不会解析为HTML。
推荐文章
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?