批改状态:合格
老师批语:
| 类数组 |
|---|
| 类似数组,长得像数组,但它又不是数组,它有两个特征 |
| 1.有length索引 |
| 2.有递增的整数索引 |
下面让我们来看看什么是类数组,请看下图

大家可以看到,用document.querySelectorAll方法访问超链接和li都是一个类数组

<body><div class="data"><a class="clj" href="">超链接1</a><a class="clj" href="">超链接2</a><a class="clj" href="">超链接3</a><a class="clj" href=""> 超链接4</a><a class="clj" href="">超链接5</a><ul class="list"><li class="item">item1</li><li class="item">item2</li><li class="item">item3</li><li class="item">item4</li><li class="item">item5</li></ul></div><script>//document.querySelectorAll 打印类数组类型console.log(document.querySelectorAll(".clj"));console.log(document.querySelectorAll(".item"));// 1. Array.from() 将“类数组”转为真正的数组,方便我们使用强大的数组方法来操作const hobby = {0: "跑步",1: "羽毛球",2: "驾驶",3: "看电影",length: 4,};let arr1 = Array.from(hobby);//用push()在尾部新增一个成员arr1.push("学习php");console.log(arr1);</script></body>
| 方法 | 含义 |
|---|---|
| createElement() | 创建dom元素 |
| querySelectorAll() | 获取dom元素 |
| querySelector() | 获取满足条件的元素集合中的第一个元素 |
| append() | 将参数做为父元素的最后一个子元素追加到列表中,无返回值 |
| prepend() | 将参数做为父元素的头部追加 |
| replaceWith() | 当前节点替换方法 |
| remove() | 删除节点,在被删除的节点上直接调用 |
| insertAdjacentElement() | (‘插入位置’, 元素) |
| afterBegin | 开始标签之后,第一个子元素 |
| beforeBegin | 开始标签之前,是它的前一个兄弟元素 |
| afterEnd | 结束标签之后,它的下一个兄弟元素 |
| beforeEnd | 结束标签之前,它的最后一个子元素 |

用 document.createElement 创建两个dom元素,div和span 并用textContent传入文本。

还可以传入到body里面,但是要用到cloneNode克隆一个span,这样span才不会从控制台消失


首先创建 ul dom元素,用for循环创建多个li 并且用 append 传入到ul里面,在用append 传入到body里面在页面中显示。


首先拿到该节点位置,然后我们用before在它前面添加一个li标签元素



可以看到之前的item3被删除了。remove不需要传值。
<script>//创建dom元素let div = document.createElement("div");let span = document.createElement("span");span.textContent = "绿水青山常在";console.log(div, span);//用append(ele,'text'),将span参数传入div中div.append(span);console.log(div);//将span传入body中并且用cloneNode()克隆一个spandocument.body.append(span.cloneNode(true));//用append 创建一个列表// 首先创建 ul dom元素const ul = document.createElement("ul");//用for循环创建多个li 并且用 append 传入到ul里面for (let i = 1; i <= 5; i++) {const li = document.createElement("li");li.textContent = `item${i}`;ul.append(li);}// 在用append 传入到body里面在页面中显示document.body.append(ul);//用prepend在父元素头部追加li = document.createElement("li");li.textContent = "我在父元素头部";li.style.background = "red";ul.prepend(li);//在任意一个节点添加,首先拿到该节点位置// 拿到li标签第三个元素const beFore = document.querySelector("li:nth-of-type(3)");// 背景改为青色beFore.style.background = "cyan";//然后我们在它前面添加一个li标签元素li = document.createElement("li");li.style.background = "yellow";li.textContent = "我在item2前面";// before 在节点前面添加beFore.before(li);//after 在参考节点后面添加li = document.createElement("li");li.textContent = "我在item2后面";li.style.background = "#ccc";beFore.after(li);//replaceWith 替换元素const lilast = document.querySelector("li:last-of-type");let a = document.createElement("a");a.textContent = "百度一下";a.href = "www.baidu.com";lilast.replaceWith(a);//remove()删除元素ul.querySelector(":nth-of-type(6)").remove();</script>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号