js.4.27

本文详细介绍了DOM操作中的父元素查找、兄弟元素同胞元素的遍历方法,如children、childNodes、firstElementChild等属性的使用。同时,展示了如何通过createElement创建元素,以及insertBefore、replaceChild和removeChild实现DOM元素的增删改查操作,为前端开发人员提供了实用的DOM操作指南。
摘要由CSDN通过智能技术生成

一.DOM的遍历

    1. 父元素查找
      children 返回(元素)子节点
      console.log(box.children);//HTMLCollection(3) [div.box1, div.box2, ul.list]
      childNode 返回子节点(包含文本(空)节点)
      console.log(box.childNodes);//NodeList(7) [text, div.box1, text, div.box2, text, ul.list, text]
      firstChild 返回第一个子节点 (包含文本)
      console.log(box.firstChild);//#text
      firstElementChild 返回第一个子(元素)节点
      console.log(box.firstElementChild);//div.box1
      lastChild 返回最后一个子节点 (包含文本)
      console.log(box.lastChild);//#text
      lastElementChild 返回最后一个子(元素)节点
      console.log(box.lastElementChild);//ul.list
      parentNode 返回父级节点
      console.log(box1.parentNode);//div.box
      parentElement 返回父级(元素节点)
      console.log(box2.parentElement);//div.box
      offsetParent 相对关系 返回第一个由定位属性的祖元素,如果没有,返回body
      console.log(list1.offsetParent);//body
  • 2.兄弟元素 同胞元素
    nextElementSibling 返回下一个兄弟元素节点
    console.log(box1.nextElementSibling);
    nextSibling 返回下一个兄弟节点 包含文本
    console.log(box1.nextSibling);
    nextElementSibling 返回上一个兄弟元素节点
    console.log(box2.previousElementSibling);
    nextSibling 返回上一个兄弟节点 包含文本
    console.log(box1.previousSibling);

二、DOM节点的增删改查

创建元素
var arr1=document.createElement(‘P’)
arr1.innerText=‘段落标签6’;
arr1.style.backgroundColor=‘yellow’
var arr2=document.createElement(‘P’)
arr2.innerText=‘段落标签7’;
arr2.style.backgroundColor=‘hotpink’
var arr3=document.createElement(‘P’)
arr3.innerText=‘段落标签8’;
arr3.style.backgroundColor=‘lightblue’
插入元素
aBtn.insertBefore(arr2,aBoxs[1])
替换元素
aBtn.replaceChild(arr3,aBoxs[4])
删除元素
aBtn.removeChild(aBoxs[3])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值