增
1.創(chuàng)建元素節(jié)點(diǎn)
var h1 = document.createElement("h1");
2.獲取body
var body = document.body;
3.拼接節(jié)點(diǎn)(把h1拼接到body中)
例1:
body.appendChild(h1);
例2:只適用于body內(nèi)部比較少元素的時(shí)候 innerHTML會(huì)覆蓋從之前的內(nèi)容
body.innerHTML = "<h1></h1>";
4.創(chuàng)建文本節(jié)點(diǎn)(被文本節(jié)點(diǎn)拼接到h1標(biāo)題內(nèi))
var text = document.createTextNode("我是標(biāo)題");
h1.appendChild(text);
5.創(chuàng)建屬性節(jié)點(diǎn)
var attr = document.createAttribute("title");
attr.value = "我是一個(gè)屬性值";//給屬性節(jié)點(diǎn)賦值
h1.setAttributeNode(attr);//把屬性節(jié)點(diǎn)拼接到h1中去
直接設(shè)置屬性值 setAttribute(name,value)
h1.setAttribute('title','我是標(biāo)題的title屬性的值');
6.在h1上面插入header元素
var header = document.createElement('header');
header.innerHTML = "我是header";
body.insertBefore(header,h1);//插入到h1上面
插入元素在前,目標(biāo)元素在后面
7.在h1下面插入footer元素
var footer = document.createElement('footer');
body.appendChild(footer);
8.創(chuàng)建a標(biāo)簽
var a = document.createElement('a');
a.innerHTML = "百度一下";
a.setAttribute('href',"http://www.baidu.com");
footer.appendChild(a);
刪除
1.刪除a標(biāo)簽
footer.removeChild(a)
不知道父元素的情況下如何刪除
a.parentNode.removeChild(a);
封裝函數(shù)刪除
function remove(obj) {
obj.parentNode.removeChild(obj);
};
remove(obj);
改
- 替換節(jié)點(diǎn) replaceChild(new.old)
創(chuàng)建img標(biāo)簽 替換a標(biāo)簽
var img = document.createElement('img');
img.setAttribute('src', "keep.jpg");
footer.replaceChild(img,a)//使用image標(biāo)簽替換a標(biāo)簽
查
1.獲取元素
getElementById
getElementsByTagName
getElementsByClassName
querySwlector()
querySwlectorAll()
2.獲取兄弟下節(jié)點(diǎn)(nextSibling)
console.log(header.nextSibling);
3.獲取兄弟上上節(jié)點(diǎn)(previousSibling)
console.log(footer.previousSibling);
4.獲取父節(jié)點(diǎn)(parentNode)
console.log(h1.parentNode);
5.獲取子節(jié)點(diǎn)(children)有可能返回一個(gè)數(shù)組
console.log(footer.children);