1、认识DOM
文档对象模型(document Object model),由W3C提出的标准,是一个使用脚本动态的访问和更新文档的内容、结构以及样式;
DOM 提供了相应的API(接口),可以对文档进行增删改查,以实现js对网页元素的静态(进行)控制,实现动态网页的功能
2、HTML 节点树
DOM 的原理是将文档装入内容,并以节点的形式解析为一棵节点树
HTML 文档就是一种树状的结构化文档
3、节点类型
1.元素节点:就是指标签
2.属性节点:就是指标签上的属性
3.文本节点:就是指标签之间的文本内容
4、获取节点的辅助方法
>> childNodes: 返回该节点下所有的子节点列表【包含空白符】(集合)【类似数组结构】
语法:父节点.childNodes
>> .hasChildNodes(); --判断是否有子节点
语法:父元素.hasChildNodes();
>> firstChild --返回第一个子节点
语法:父元素.firstChild
>> lastChild --返回最后一个子节点
语法:父元素.lastChild
>> .previousSibling --返回上一个兄弟节点
语法:父元素.previousSibling
>> .nextSibling --返回写一个兄弟节点
语法:父元素.nextSibling
>> parentNode(靠谱)
语法:子节点.parentNode --返回父节点
>> children --返回所有的节点(靠谱,不包含空白符)
语法:父元素.children
5、节点属性
5.1 节点名字:nodeName
1.元素节点的 nodeName 与标签名字一样;
2.属性节点的 nodeName 与属性名一样;
3.文本节点的 nodeName 固定值为 #text;
5.2 节点值: nodeValue
1.元素节点的 nodeValue 为Undefined 或者 null
2.属性节点的 nodeValue 为属性值
3.文本节点的 nodeValue 为文本内容
5.3 节点类型: nodeType
1.元素节点的 nodeType 为 1
2.属性节点的 nodeType 为 2
3.文本节点的 nodeType 为 3
// 获取节点的方法
1、获取节点方法(W3C)
>>通过 ID 获取标签(获取一个标签)
document.getElementByID(id);
>> 通过标签名获取:(获取一个标签的集合、类似数组结构)
document.getElementsByTagName(tagname);
>> 通过 name 获取标签(获取的是一个集合)
document .getElementsByName(name);
>> 通过 class 名字获取标签(获取一个标签的集合、类似数组结构)只支持IE9及以上
document.getElementsByClassName(classname)
2、其他方法:
>> 获取HTML标签(所有浏览器都支持的)
document.documentElement
>> 获取body标签
document.body
>> 通过 form 的 name 获取表单
例如:console.log(
document.loginForm.username);
语法:document.表单名字
document.表单名字.表单元素名
3、强大的 query【无法获取动态添加的 dom 节点】
document.querySelector(css选择器); --返回找到的第一个元素
document.querySelector('#nav');
document.querySelector('li');
document.querySelectorAll(css选择器) --返回找到的所有元素
// 获取属性
1、获取属性:
>> 元素.attributes --获取元素属性集合
console.log(attributes);
console.log(attributes[0]);
>> 元素.属性名
【因为class是关键字,所以要写上className;用于获取元素】
console.log(baidu.className);
>> 元素.getAttribute(属性名)
【用于获取某一个属性】
console.log(baidu.getAttribute('href'));
[如果是class就不需要再用className了,因为''封装了不会起冲突]
console.log(baidu.getAttribute('class'));
2、设置属性:
>> 元素.属性名 = '属性值';
baidu.style.color = 'red';
>> 元素.setAttribute(属性名,属性值);
baidu.setAttribute('title','您点击之后不会发生改变');
3、移除属性
元素.removeAttribute(属性名);
4、判断是否有某一个属性
元素.hasAttribute(属性名) --返回值是一个布尔值
5、HTML5 自定义属性操作
>> element.dataset.自定义属性名(如:data-index)
>> element.getAttribute('data-index');
// 操作CSS样式
>> 元素.style.css属性名 = css属性值;【大多数都要加''因为是值】
demo.style.height = '50px';
demo.style.border = '2px solid red';
注意:【如果css单词是通过链接的单词,则需要写成驼峰式命名】
如:demo.style.borderBottom = '2px solid red';
【因为float是js中的保留字,所以要写为cssFloat】
如: demo.style.cssFloat = 'right';
>> cssText【可以帮助我么批量的设置CSS样式】
demo.style.cssText += 'width: 400px;height: 50px;';
>> 添加 classname (推荐使用)
提前在css中写好class,接下来动态添加class,比如:demo.className = 'demo box';
demo.className = 'demo box';