节点操作
节点操作实际是利用DOM树把节点划分为不同的层次关系,常见父子兄弟级关系
节点属性:
节点一般有三个属性:nodeType节点类型(其中元素节点值为1,属性节点值为2,文本节点值为3)、nodeName节点名称、nodeValue节点值
父级节点和父级元素获取:
.parentNode父级节点、.parentElement父级元素;找不到就返回null:
<body><div><div class="box"></div></div><script>var box = document.getElementsByClassName('box')[0];var boxFather = box.parentNode;console.dir(boxFather);</script></body>
子级节点
.childNodes:得到的是一个节点集合,包含元素节点、文本节点;这样会带来不便的麻烦,因此出现了:仅可以获取所有元素节点的方法:.children、获取第一个子级节点的方法:.firstChild、获取第一个子级元素节点的方法:.firstElementChild、获取最后一个子级节点的方法:.lastChild、获取最后一个子级元素节点:lastElementChild
<body><ul><li>1</li><li class='lis'>2</li><li>3</li></ul><script>var ulList = document.querySelector('ul');var listLi = ulList.childNodes;var Li = ulList.children;console.log(listLi); //NodeList(7) [text, li, text, li.lis, text, li, text]console.log(Li); //HTMLCollection(3) [li, li.lis, li]console.log(listLi[0].nodeType); //3表示文本console.log(listLi[1].nodeType); //1元素(标签)</script></body>
兄弟节点:
返回当前元素的下一个兄弟节点:node.nextSibling、返回上一个兄弟节点:node.previousSibling、返回下一个元素节点:node.nextElementSibling、返回上一个元素节点:node.previousElementSibling
<body><ul><li>1</li><li class='lis'>2</li><li>3</li></ul><ul><li>4</li><li class='lis'>5</li><li>6</li></ul><script>var ulList = document.querySelector('ul');console.log(ulList.nextSibling); //#text,获取下一个节点console.log(ulList.nextElementSibling); //<ul>...</ul>,获取下一个元素节点console.log(ulList.previousSibling); //#text,获取上一个节点console.log(ulList.previousElementSibling); //null,获取上一个元素节点</script></body>
创建节点:
1.创建元素节点:document.createElement(‘标签’); 2.将创建的元素节点追加到某个节点:父级节点.appendChild(创建的元素节点),此方法是在后面添加的元素节点,如果想要在某个节点前面添加元素节点,那么可以使用:父级节点.insertBefore(创建的元素节点,某个节点);
<body><ul><li>1</li></ul><script>var ulList = document.querySelector('ul');var liChild = document.createElement('li');liChild.innerHTML = 'hello';// ulList.appendChild(liChild);ulList.insertBefore(liChild, ulList.children[0]);</script></body>
删除节点:
node.removeChild()用来删除node的子元素,括号里传入要删除的子元素;
克隆节点:
node.cloneNode()用来克隆node,如果括号里面传入false或者不传参数,则只克隆标签,不克隆内容;若括号里传入true则和内容一起克隆。
提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:810665436@qq.com联系笔者 删除。
笔者:苦海