Document对象
document
DOM提供,作为解析的入口提供了属性和方法,提供了可以直接使用的对象
Document类型:Document是一个构造函数,具有prototype原型属性
属性和方法多源于prototype原型上

DOM查询

getElement或getElements…方法查询

通过id属性值定位
var p1=document.getElementById(‘p1’);
console.log(p1);
定位的内容–打印的是HTML的源代码
得到的真正内容是HTML对应元素的DOM对象

通过class属性值定位
var p2=document.getElementsByClassName(‘p2’);
console.log(p2);
返回值是一个数组
用于存储多个元素
注意
IE8及之前不兼容

通过name属性值定位
var p3=document.getElementsByName(‘p3’);
console.log(p3);
name允许重复,得到的元素可能是多个
返回值是一个数组–用于存储多个元素

通过元素名称定位
var pElements = document.getElementsByTagName(‘p’)
console.log(pElements);
返回值是一个数组–用于存储多个元素
注意事项
不需要去了解为什么可以实现这样的效果
Document对象具有哪些属性和方法
Document对象的属性和方法如何使用
Document对象的属性和方法使用时,需要注意哪些问题

quertSelector(selector)和quertSelectorAll(selector)

quertSelector(selector)
定位与指定选择器匹配的第一个HTML元素

quertSelectorAll(selector)
定位与指定选择器匹配的所有元素
参数
选择器
都是CSS中的选择器用法

id属性值
var p1=document.querySelector(‘#p1’);
var p1=document.querySelectorAll(‘#p1’)
console.log(p1);

class属性值
var p2=document.querySelector(‘.p2’)
var p2=document.querySelectorAll(‘.p2’);
console.log(p2);

DOM对比

getElement或getElements…
优点
使用简单-单个方法使用简单
性能比较好
缺点
使用麻烦–方法数量多
存在浏览器兼容问题
特点
跟随HTML页面内容变化而变化
通过指定方法获取指定HTML标签后
更新了HTML中内容后,结果也会更新

quertSelector(selector)和quertSelectorAll(selector)
优点
使用简单–方法数量少
没有浏览器兼容问题
缺点
需要配合CSS选择器使用
性能比较差
特点
一旦获取之后就和HTML页面内容无关了
通过指定方法获取指定的HTML标签后
得到的结果与HTML页面内容无关

返回值

getElements…方法
返回值是动态NodeList,NodeList对象
的内容跟随HTML页面变化而变化

quertSelectorAll(selector)
返回值是静态NodeList,NodeList对象
的内容不会跟随HTML页面变化而变化

Document对象的属性

获取当前HTML页面的根标签() console.log(document.documentElement);

获取当前HTML页面的标签 console.log(document.head);

body属性 — 获取当前HTML页面的标签
console.log(document.body);

forms属性 — 获取当前HTML页面的所有表单元素
console.log(document.forms);

images属性 — 获取当前HTML页面的所有图片元素
console.log(document.images);

创建节点

创建元素节点
var newLi=document.createElement(‘li’)

创建文本节点
var textNode=document.createTextNode(‘木瓜’)
将文本节点添加到元素节点上
parentNode.appendChild(childNode)
newLi.appendChild(textNode)

创建属性节点
创建属性节点
createAttribute(attrName)
attrName表示属性的名称
为属性节点设置对应的值
attrNode.nodeValue=value
属性节点不是父级节点也不是子级节点
设置属性节点
parentName.setAttribuuteNode(attr)
parentName
表示新的元素名称

打赏

发表评论

邮箱地址不会被公开。 必填项已用*标注