DOM操作3:属性操作
非表单元素的属性
href、title、id、src、className
var link = document.getElementById('link');
console.log(link.href);
console.log(link.title);
var pic = document.getElementById('pic');
console.log(pic.src);
- innerHTML 和 innerText
var box = document.getElementById('box');
box.innerHTML = '我是文本<p>我会生成为标签</p>';
console.log(box.innerHTML);
box.innerText = '我是文本<p>我不会生成为标签</p>';
console.log(box.innerText);
- HTML转义符
" "
‘ '
& &
< < // less than 小于
> > // greater than 大于
空格
© ©
表单元素属性
- value 用于大部分表单元素的内容获取(option除外)
- type 可以获取input标签的类型(输入框或复选框等)
- disabled 禁用属性
- checked 复选框选中属性
- selected 下拉菜单选中属性
自定义属性操作
- getAttribute() 获取标签行内属性
- setAttribute() 设置标签行内属性
- removeAttribute() 移除标签行内属性
- 与element.属性的区别: 上述三个方法用于获取任意的行内属性。
样式操作
- 使用style方式设置的样式显示在标签行内
var box = document.getElementById('box');
box.style.width = '100px';
box.style.height = '100px';
box.style.backgroundColor = 'red';
-
注意
通过样式属性设置宽高、位置的属性类型是字符串,需要加上px
类名操作
- 修改标签的className属性相当于直接修改标签的类名
var box = document.getElementById('box');
box.className = 'clearfix';
DOM操作3:节点操作
var body = document.body;
var div = document.createElement('div');
body.appendChild(div);
var firstEle = body.children[0];
body.insertBefore(div,firstEle);
body.removeChild(firstEle);
var text = document.createElement('p');
body.replaceChild(text, div);
节点层级
var box = document.getElementById('box');
console.log(box.parentNode);
console.log(box.childNodes);
console.log(box.children);
console.log(box.nextSibling);
console.log(box.previousSibling);
console.log(box.firstChild);
console.log(box.lastChild);
childNodes
和children
的区别:
-
childNodes
获取的是子节点,children
获取的是子元素 -
nextSibling
和previousSibling
获取的是节点 -
获取元素对应的属性是
nextElementSibling
和previousElementSibling
-
获取元素的是
nextElementSibling
和previousElementSibling
有兼容性问题,IE9以后才支持
总结
- 节点操作,方法
appendChild()
insertBefore()
removeChild()
replaceChild()
- 节点层次,属性
parentNode
childNodes
children
nextSibling/previousSibling
firstChild/lastChild