JavaScript中innerHTML, innerText和value的区别是什么?
当前回答
innerText属性设置或返回指定节点及其所有后代的纯文本文本内容,而innerHTML属性获取和设置元素中的纯文本或HTML内容。与innerText不同,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。
其他回答
要添加到列表中,innerText将保留您的文本转换,innerHTML习惯。
InnerText将仅以纯文本形式返回页面的文本值,其中每个元素在换行符上,而innerHTML将返回body标记内所有内容的HTML内容,而childNodes将返回一个节点列表,顾名思义。
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>
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格式可能 被包括。 innerHTML将显示值并应用任何HTML格式。