JavaScript中innerHTML, innerText和value的区别是什么?
当前回答
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和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将保留您的文本转换,innerHTML习惯。
简单地说:
innerText将显示值,并忽略任何HTML格式可能 被包括。 innerHTML将显示值并应用任何HTML格式。