innerHTML、innerText、textContent和Jquery中text()、html()、val()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014465934/article/details/87945069

1.innerHTML

innerHTML可获取或设置指定元素标签内的 html内容,从该元素标签的起始位置到终止位置的全部内容(包含html标签)。

获取元素的内容:element.innerHTML;
给元素设置内容:element.innerHTML =htmlString;

代码示例为:

<p id="test"><font color="#000">获取段落p的 innerHTML</font></p>
document.getElementById("test").innerHTML

输出内容为:<font color="#000">获取段落p的 innerHTML</font>

javascript获取节点文本值:
(1)原生js写法 document.getElementById(‘test’).innerHTML
(2)jQuery写法 $(’#test’).html()

outerHTML:

除了包含innerHTML的全部内容外, 还包含对象标签本身。

<div id="test">
<span style="color:red">test1</span> test2
</div>

//test.innerHTML
“<span style="color:red">test1</span> test2 ”
//text.outerHTML
<div id="test"><span style="color:red">test1</span> test2</div>

2.innerText

innerText可获取或设置指定元素标签内的文本值,从该元素标签的起始位置到终止位置的全部文本内容(不包含html标签)。

获取元素的内容:element.innerText;
给元素设置内容:element.innerText = string;

代码示例为:

<p id="test"><font color="#000">获取段落p的 innerHTML</font>测试测试</p>
document.getElementById("test").innerHTML

输出内容为:获取段落p的 innerHTML试测试

3.textContent与innerText

innerText是IE的私有实现,但也被除FF之外的浏览器所实现,textContent 则是w3c的标准API,现在IE9也实现了。

它们区别只要有两点
1.innerText不能返回script标签里面的源码,textContent则可以,在不支持textContent的浏览器,我们可以使用text与innerHTML代替。
2.textContent会保留空行与空格与换行符,innerText则只会保留换行符。

参考文章:https://www.cnblogs.com/rubylouvre/archive/2011/05/29/2061868.html

4.value属性

属性可设置或返回密码域的默认值。获取文本框的值。

value 属性为 input 元素设定值。

对于不同的输入类型,value 属性的用法也不同:
1.type=“button”, “reset”, “submit” - 定义按钮上的显示的文本
2.type=“text”, “password”, “hidden” - 定义输入字段的初始值
3.type=“checkbox”, “radio”, “image” - 定义与输入相关联的值

5.Jquery中text()、html()、val()

js获取text、html、属性值、value的方法:
document.getElementById("test").innerText;
document.getElementById("test").innerHTML;
document.getElementById("test").id;
document.getElementById("test1").value;

jQuery获取text、html、属性值、value的方法:
$("#test").text()或者$("#test").innerText
$("#test").html()或者$("#test").innerHTML
$("#test").attr("id")
$("#test").attr("value")或者$("#test1").val()或者$("#test1").value

可以参考:
https://www.cnblogs.com/jongsuk0214/p/6930876.html
https://www.cnblogs.com/mlbblkss/p/7135871.html
https://www.cnblogs.com/rubylouvre/p/4321442.html

猜你喜欢

转载自blog.csdn.net/u014465934/article/details/87945069