js web API-DOM

DOM

题目

  • DOM是哪种数据结构(除了树难道还能是图???)
  • DOM操作常用的api
  • attribute和property的区别
  • 一次性插入多个DOM,考虑性能

知识点

DOM本质

DOM节点操作

获取DOM节点
  • document.getElementById()//元素
  • document.getElementsByTagName()//集合
  • document.getElementsByClassName()//集合
  • document.querySelectorAll()//集合
DOM节点的property和arrtribute
//property
p1.style.width='100px'
console.log(p1.style.width)
p1.className='red'
console.log(p1.nodeName)//p
console.log(p1.nodetype)//1

//arrtribute
p1.setArribute('data-name','imooc')
console.log(p1.getArrtribute('data-name'))
p1.setArritribute('style','font-size:50px;')
console.log(p1.getArrtirbute('style'))

property与arrtribute得区别

  • property能够从attribute中得到同步;
  • attribute不会同步property上的值;
  • attribute和property之间的数据绑定是单向的,attribute->property;
  • 更改property和attribute上的任意值,都会将更新反映到HTML页面中;

最后为了更好的区分attribute和property,基本可以总结为attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。

DOM结构操作

  • 新增/插入节点
const p1=document.createElement//新增
p1.innerHTML='this is p1'
//插入
div.appendChild(p1)//现有节点使用appendChild会移动该节点
  • 获取子节点列表,获取父元素
p.parentNode
div.childNodes//此时获取的有text有节点,,不符合需求

关于获取子元素筛选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id='div1'>
        <p>p1</p>
        <p>p2</p>
    </div>
    <script>
        const div=document.getElementById('div1')
        const divChilsNodes=div.childNodes
        const divChilds=Array.prototype.slice.call(div.childNodes).filter(
            child=>{
                if (child.nodeType===1)
                {
                    return true
                }
                return false
            }
        )
        console.log(divChilds);
    </script>
</body>
</html>

在这里插入图片描述
若不筛选,文本内容也被当做子节点返回

  • 删除子节点
  const div=document.getElementById('div1')
  const child=div.childNodes
  div.removeChild(child[0])

DOM性能

  • DOM操作十分昂贵,避免频繁操作
  • 将频繁操作改为一次性操作,
  • 对DOM查询做缓存
    缓存
    在这里插入图片描述
    将频繁操作改为一次性操作
    在这里插入图片描述
    fragment 像是一个临时节点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值