博客列表 >DOM常用操作

DOM常用操作

手机用户1620888567
手机用户1620888567原创
2023年02月22日 19:46:04511浏览

DOM 常用操作-2

1. 增删改(写操作)

  1. createElement(): 创建新元素
  2. createDocumentFragment(): 创建文档片断
  3. append(): 追加新元素
  4. before(): 在前面追加
  5. after(): 在后面追加
  6. cloneNode(): 克隆节点
  7. replaceChild(): 替换元素
  8. remove(): 移除元素
    ```
    <!DOCTYPE html>

    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>增删改(写操作)</title>
    </head>
    <body>
    <script>
    /* 1. 创建元素: createElement() 2. 追加元素: append() 3. 创建片断: createDocumentFragment 4. 后面添加: after() 5. 前面添加: before() 6. 克隆节点: cloneNode(true) 7. 替换子元素: replaceChild() 8. 删除元素: remove() /

    // 1. 创建
    const ul = document.createElement(‘ul’)

    // 2. 添加
    document.body.append(ul)

    // 为ul添加一些子元素
    // for (let i = 1; i <= 5; i++) {
    // const li = document.createElement(‘li’)
    // li.append(‘item-‘ + i)
    // ul.append(li)
    // }

    // 3. 文档片断
    // 使用文档片断来优化这种创建过程,提升渲染效率
    const frag = document.createDocumentFragment()
    for (let i = 1; i <= 5; i++) {
    const li = document.createElement(‘li’)
    li.append(‘demo-‘ + i)
    frag.append(li)
    }
    // 最后再统一添加到页面中的UL中
    ul.append(frag)

    // 4. 后面: after
    // (1)必须先找到插入点,如第3个
    const three = ul.querySelector(‘:nth-child(3)’)
    // (2)创建新元素
    let li = document.createElement(‘li’)
    li.append(‘新的<li>‘)
    // (3)插入到指定位置
    three.after(li)

    // 5. 前面: before
    // 还是第3个元素,但是在前面插入
    // (1)创建新元素
    li = document.createElement(‘li’)
    li.append(‘新的<li>-1’)
    // (3)插入到指定位置
    three.before(li)

    // 6. 克隆: coneNode(true)
    // true: 深度克隆,要不到内部的所有后代元素
    let newLi = li.cloneNode(true)
    console.log(newLi)
    ul.append(newLi)

    // 7. 替换/更新: replaceChild(新,原)
    const last = ul.lastElementChild
    let h2 = document.createElement(‘h2’)
    h2.append(‘被替换的元素’)
    ul.replaceChild(h2, last)

    // 8.删除
    // 被删除
    // ul.removeChild(ul.querySelector(‘:last-child’))
    // 自杀:在当前元素上调用, 自宫
    ul.querySelector(‘:last-child’).remove()
    </script>
    </body>
    </html>

  1. ## 2. 元素内容
  2. 1. `textContent`: 全部内容(包括 js,css,隐藏内容)
  3. 2. `innerText`: 返回已渲染(可见)内容
  4. 3. `innerHTML`: 替换元素内容(html)
  5. 4. `outerHTML`: 替换元素自身(html)

<!DOCTYPE html>

<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>元素内容</title>
</head>
<body>
<h2>Hello world</h2>
<div class="box">
<style>
h2 {
color: red;
}
</style>
<h2>通知</h2>
<span style="display: none">试用期员工不参加</span>
<p>今天下午17:00开会, 开发部, 运营部全体参加~~</p>
</div>

<script>
/* 1. textContent: 全部内容(包括 js,css,隐藏内容) 2. innerText: 返回已渲染(可见)内容 3. innerHTML: 替换/读取元素”内容”(html) 4. outerHTML: 替换/读取元素”自身”(html) /

console.log(document.querySelector(‘h2’).textContent)
console.log(document.querySelector(‘.box’).textContent)
console.log(document.querySelector(‘.box’).innerText)
console.log(document.querySelector(‘.box’).innerHTML)
document.querySelector(‘.box’).innerHTML = ‘<h1>Hello 朱老师</h1>‘

// document.querySelector(‘.box’).outerHTML = null

// 删除
// remove() === (outerHTML = null)
document.querySelector(‘.box’).remove()
</script>
</body>
</html>

  1. ## 3. 指定位置插入
  2. ### 3.1 插入位置
  3. 1. `beforebegin`:元素自身的前面
  4. 2. `afterbegin`:插入元素内部的第一个子节点之前
  5. 3. `beforeend`:插入元素内部的最后一个子节点之后
  6. 4. `afterend`:元素自身的后面
  7. ### 3.2 API 方法
  8. 1. `insertAdjacentElement()`:指定位置插入**元素**
  9. 2. `insertAdjacentText()`: 指定位置插入**文本**节点 无论是什么都原样显示
  10. 3. `insertAdjacentHTML()`: 指定位置插入**元素节点**(DOMString) 可以识别html
  11. ![image.png](https://note.youdao.com/yws/res/7/WEBRESOURCE6715675cd4e7aecd3c1ad1b8386d4267)
  12. ![image.png](https://note.youdao.com/yws/res/c/WEBRESOURCEb09aee329506cd74f82f4d4736a1cbdc)

<!DOCTYPE html>

<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>指定元素标签的位置插入</title>
</head>
<body>
<ul class="list">
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
<script>
// 1 插入位置
// 1. beforebegin:元素自身的前面
// 2. afterbegin:插入元素内部的第一个子节点之前
// 3. beforeend:插入元素内部的最后一个子节点之后
// 4. afterend:元素自身的后面

// 2 API 方法
// 1. insertAdjacentElement():指定位置插入元素
// 2. insertAdjacentText(): 指定位置插入文本节点
// 3. insertAdjacentHTML(): 指定位置插入元素节点(DOMString)

const ul = document.querySelector(‘.list’)

const h3 = document.createElement(‘h3’)
h3.textContent = ‘列表2121’
// insertAdjacentElement:第2个参数是元素类型

ul.insertAdjacentElement(‘afterend’, h3)

ul.insertAdjacentText(‘afterbegin’, ‘<p style="color:red">Hello world AdjacentText<p>‘)

// 直接将可以将字符串解析为html元素
ul.insertAdjacentHTML(‘afterbegin’, ‘<p style="color:red">121212<p>‘)
</script>
</body>
</html>

  1. ## 4. dataset 对象
  2. 1. 预定义属性: `id,class,style, title...`
  3. 2. 自定义属性: `data-`前缀
  4. 3. 注: `data-`不要写,蛇形->驼峰

<!DOCTYPE html>

<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>dataset对象</title>
</head>
<body>
<h3 style="color: red">Hello</h3>
<div data-username="朱老师" data-my-email="abc@qq.com">用户信息</div>
<script>
// dataset对象:读取自定义属性
// 自定义属性: data-前缀的
// 预定义属性/预置属性: id,class,style,src,type,...

// 预定义属性
console.log(document.querySelector(‘h3’).style.color)

// 自定义属性:dataset
console.log(document.querySelector(‘div’)[‘data-username’])
console.log(document.querySelector(‘div’).dataset[‘username’])
console.log(document.querySelector(‘div’).dataset.username)
console.log(document.querySelector(‘div’).dataset[‘myEmail’])
console.log(document.querySelector(‘div’).dataset.myEmail)
console.log(document.querySelector(‘div’).getAttribute(‘data-my-email’))
</script>
</body>
</html>

  1. ## 5. `getComputedStyle`对象
  2. - 计算样式: 元素上的全样样式,包括行内,文档,外部等
  3. - 只读
  4. -

<!DOCTYPE html>

<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>计算样式: getComputedStyle</title>
<link rel="stylesheet" href="style.css" />
<style>
h3 {
width: 200px;
height: 50px;
}
</style>
</head>
<body>
<h3 style="color: red">Hello 晚上好</h3>

<script>
const h3 = document.querySelector(‘h3’)
console.log(h3.style.color)
console.log(h3.style.width)
console.log(h3.style.height)
// 当前元素的最终样式: 行内,文档,外部3个样式作用的结果
// 用计算样式就可以全部获取到
// rgb(255, 0, 0) = red (rgb(红, 绿, 蓝))
console.log(window.getComputedStyle(h3).color)
// width,height 返回 字符串
console.log(window.getComputedStyle(h3).width)

let width = window.getComputedStyle(h3).width
// 将width转为整数
width = parseInt(width)
console.log(width + 100)

h3.style.width = width + 100 + ‘px’
// h3.style.width = ‘300px’

// classList: 操作css中的 class属性
</script>
</body>
</html>

<!DOCTYPE html>

<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>toDoList:留言板</title>
</head>
<body>
<input type="text" onkeydown="addComment(this)" placeholder="请留言" autofocus />
<!-- 留言的区域 -->
<ul class="list"></ul>
<script>
function addComment(ele) {

if (event.key === ‘Enter’) {

if (ele.value.length === 0) {
alert(‘忘了写点啥了吧?’)
ele.focus()
return false
} else {

const ul = document.querySelector(‘.list’)

ele.value += ‘<button onclick="del(this.parentNode)">删除</button>‘

ul.insertAdjacentHTML(‘afterbegin’, <li>${ele.value}</li>)


ele.value = null
}
}
}


function del(ele) {
console.log(ele)
return confirm(‘是否真的删除?’) ? ele.remove() : false
}
</script>
</body>
</html>

```

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议