JS学习-DOM
DOM
DOM树
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple DOM example</title>
</head>
<body>
<section>
<img src="dinosaur.png" alt="img">
<p>Here we will add a link to the
<a href="https://www.mozilla.org/">Mozilla homepage</a>
</p>
</section>
</body>
</html>
- 元素节点: head,body...
- 根节点: html(其他标记词汇,如SVG和定制XML将有不同的根元素)。
- 子节点: img,p->section
- 后代节点: img,p,a->section
- 父节点: section->img,p,a
- 兄弟节点: img->p
- 文本节点: #text: .....
DOM操作
-
获取DOM节点
document.querySelector('select'); document.querySelectorAll('option'); //更旧的方法:document.getElementById() document.getElementsByTagName() -
改变节点文本
searchNav.textContent = 'baidu' -
改变链接URL
searchNav.href = 'http://www.baidu.com' -
创建DOM节点
var sectionA = document.createElement('p'); -
创建文本节点
var txt = document.createTextNode('sectionA txt') -
把文本节点绑定到DOM节点
sectionA.appendChild(txt) -
插入DOM树
document.querySelector('article').appendChild(sectionA) -
移动DOM节点: 把文章内第一个超链接下移到article的底部
document.querySelector('article').appendChild(document.querySelector('a')) -
删除DOM节点: 删除文章第一个超链接
document.querySelector('article').removeChild(document.querySelector('a')) -
操作样式
- 通过js直接操作style
document.querySelector('a').style.color = '#000' - 通过添加属性class
.text-black{color: #000;}document.querySelector('a').setAttribute('class','text-black');
- 通过js直接操作style

浙公网安备 33010602011771号