JavaScript中你可能不懂的DOM
首先来看看DOM继承树
DOM document object moble
DOM 定义了表示和修改文档的方法。DOM对象即宿主对象,由浏览器厂家定义,用来操作HTML和XML功能的集合。也有人称dom为html和xml的接口
- document HTMLDocument Document的关系
看如下图
显然很明显了
document–>HTMLDocument.prototype–>Document.prototype
再看如下代码
Document.prototype.abc = '123'
HTMLDocument.prototype.abcd = '456'
这都是可以,可见document的原型链上有HTMLDocument.prototype和Document.prototype
text(文本节点)和comment(注释节点)
通过继承树,我们发现节点的继承和CharacterData。我们都知道nodeValue只有文本节点注释节点才有,我们打开CharacterData.prototype发现了nodeValue,看来它们来自这里,所以其他的节点没有了。
HTMLElement发现它后面有很多东西,但是都比较熟悉,都是标签。
也就是我们在HTMLElement上加属性,那么所有标签都具有了,如果只想它自己上独有,那么就在它身上加。
<div></div>
<script>
var body=document.getElementsByTagName('body')[0];
var div=document.getElementsByTagName('div')[0];
HTMLElement.prototype.abc='123';
</script>
应该比较清楚了!
注意:
- getElementById()定义在Document.prototype上,即Element节点上不能使用
- getElementsByName() 定义在HTMLDocument.prototype
- getElementsByTagName(),getElementsByClassName(),querySelector(),querySelectorAll() 定义在Document.prototype和Element.prototype
- HTMLDocument.prototype定义了两个个属性 , body、 head , 分别代表了body和head标签
- Document.prototype定义了一个属性 documentElement属性,指代文档的根元素,即总是代表着整个html
可以在控制台上试一下