首页 技术 正文
技术 2022年11月23日
0 收藏 485 点赞 4,871 浏览 1551 个字

节点操作

 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);

案例:

选择水果

节点属性

  • nodeType 节点的类型

    • 1 元素节点

    • 2 属性节点

    • 3 文本节点

  • nodeName 节点的名称(标签名称)

  • nodeValue 节点值

    • 元素节点的nodeValue始终是null

模拟文档树结构

DOM——节点操作

function Node(option) {
this.id = option.id || '';
this.nodeName = option.nodeName || '';
this.nodeValue = option.nodeValue || '';
this.nodeType = 1;
this.children = option.children || [];
}var doc = new Node({
nodeName: 'html'
});
var head = new Node({
nodeName: 'head'
});
var body = new Node({
nodeName: 'body'
})
doc.children.push(head);
doc.children.push(body);var div = new Node({
nodeName: 'div',
nodeValue: 'haha',
});var p = new Node({
nodeName: 'p',
nodeValue: '段落'
})
body.children.push(div);
body.children.push(p);function getChildren(ele) {
for(var i = 0; i < ele.children.length; i++) {
var child = ele.children[i];
console.log(child.nodeName);
getChildren(child);
}
}
getChildren(doc);

节点层级

DOM——节点操作

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

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860