转行前端:DOM的增删改查

82 阅读1分钟

createElement:创建一个元素标签(元素对象)

var newP=document.createElement([标签名])

createTextNode

appendChild:把一个元素对象插入到指定容器的末尾

[container].appendChild([newEle])

insertBefore:把一个元素对象插入到指定容器中某一个元素标签之前

[container].insertBefore([newEle],[oldEle])

var newP=document.createElement('p')document.body.appendChild(newP)

var newA=document.createElement('a')document.body.insertBefore(newA,box)

cloneNode:把某一个节点进行克隆

[curEle].cloneNode():浅克隆,只克隆当前的标签 

[curEle].cloneNode(true):深克隆,当前标签及其里面的内容都一起克隆了 

var cloneA=newA.cloneNode(true);
document.body.appendChild(cloneA);

removeChild:在指定容器中删除某一个元素

document.body.removeChild(newP);

set/get/removeAttribute:设置/获取/删除当前元素的某一个自定义属性

var oBox=document.getElementById('box');

1、把当前元素作为一个对象,在对象对应的堆内存中新增一个自定义的属性

oBox.myIndex=10;//=>设置

console.log(oBox['myIndex']);//=>获取

delete oBox.myIndex//=>删除

2、基于attribute等dom方法完成自定义属性的设置

oBox.setAttribute('myColor','red')//=>设置

oBox.getAttribute('myColor')//=>获取

oBox.removeAttribute('mycolor')//=>删除

以上两种机制属于独立的运作体制,不能混淆使用

第一种是基于对象键值对操作方式,修改当前元素对象的堆内存空间来完成

第二种是直接修改页面中HTML标签的结构来完成

(此种方法设置的自定义属性可以在结构上呈现出来)

基于setAttribute设置的自定义属性都是字符串

oBox.setAttribute('n',100)
oBox.n//=>undefined
oBox.getAttribute('n')//=>100

oBox.m=200;
oBox.getAttribute('m')//=>ull
oBox.m//=>200