Blogger Information
Blog 18
fans 0
comment 0
visits 11020
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
210406 类数组 获取遍历DOM元素 向元素添加文本 获取元素的自定义属性值 DOM元素增删改查 CSS样式操作
xyphpblog
Original
601 people have browsed it

1. 类数组

  • 本身是对象
  • 有length属性
  • 有递增的索引

类数组可以转为数组并使用数组的方法操作

  1. //结构类似数组,但是对象
  2. const color = {
  3. 0: "white",
  4. 1: "blue",
  5. 2: "yellow",
  6. 3: "green",
  7. length: 4
  8. };
  9. console.log(color);
  10. //{0: "white", 1: "blue", 2: "yellow", 3: "green", length: 4}
  11. console.log(color.length);
  12. //4
  13. console.log(color[2]);
  14. //yellow
  15. console.log(Array.isArray(color));
  16. //false
  17. console.log(typeof (color));
  18. //object
  19. console.log(color instanceof Object);
  20. //true
  21. //转为数组 方法 1
  22. let arr = Array.from(color);
  23. console.log(Array.isArray(arr));
  24. //true
  25. console.log(arr);
  26. //["white", "blue", "yellow", "green"]
  27. //转为数组 方法 2
  28. Object.defineProperty(color, Symbol.iterator, {
  29. value() {
  30. let index = 0;
  31. const keys = Object.keys(this);
  32. return {
  33. next: () => {
  34. return {
  35. done: index >= keys.length - 1,
  36. value: this[keys[index++]]
  37. };
  38. }
  39. };
  40. }
  41. });
  42. // colors 数组
  43. let colors = [...color];
  44. console.log(Array.isArray(colors));
  45. //true
  46. //向colors末端添加一个元素
  47. colors.push("orange");
  48. console.log(colors);
  49. // ["white", "blue", "yellow", "green", "orange"]

2. 获取DOM元素

  1. <ul class="list">
  2. <li class="item">item1</li>
  3. <li class="item">item2</li>
  4. <li class="item">item3</li>
  5. <li class="item">item4</li>
  6. <li class="item">item5</li>
  7. </ul>
  • document.querySelectorAll() 获取满足条件的元素集合
  1. const items = document.querySelectorAll(".list .item");
  2. console.log(items);
  3. //forEach
  4. //item:当前元素(必须)
  5. //index:索引(可选)
  6. //items: 遍历的数组(可选)
  7. items.forEach(function (item, index, items) {
  8. console.log(index);
  9. console.log(item);
  10. })
  11. //简化
  12. items.forEach((item) => console.log(item));
  13. //NodeList内置迭代器接口, 可用for...of遍历
  14. for (const iterator of items) {
  15. console.log(iterator);
  16. }
  • document.querySelector 获取满足条件的元素集合 的第一个元素
  1. //获取满足条件的元素集合 的第一个元素
  2. first = document.querySelector(".list .item");
  3. console.log(first);
  4. first.style.background = "skyblue";
  5. let list = document.querySelector(".list");
  6. console.log(list);
  • 获取特定元素
  1. //快速获取特定元素
  2. //body
  3. console.log(document.body);
  4. //head
  5. console.log(document.head);
  6. //title
  7. console.log(document.title);
  8. //html
  9. console.log(document.documentElement);

3. DOM树遍历

DOM树中所有内容都是节点(node)

例:

  1. <ul class="list">
  2. <li class="item">item1</li>
  3. <li class="item">item2</li>
  4. <li class="item">item3</li>
  5. <li class="item">item4</li>
  6. <li class="item">item5</li>
  7. </ul>

遍历

  1. let nodes = document.querySelector(".list");
  2. console.log(nodes.childNodes);
  3. // console.log(nodes.children);
  4. let items = nodes.children;
  5. //得到的是 类数组
  6. //转为数组
  7. let arr = [...items];
  8. arr.forEach(element =>
  9. console.log(element)
  10. );
  11. //第一个元素
  12. let first = arr[0];
  13. first.style.background = "lightgrey";
  14. console.log("first: ", first);
  15. //最后一个元素
  16. let last = arr[arr.length - 1];
  17. last.style.background = "lightblue";
  18. console.log("last: ", last);
  19. //第二个元素
  20. let second = first.nextElementSibling;
  21. second.style.background = "yellow";
  22. //倒数第二个
  23. let secondLast = last.previousElementSibling;
  24. secondLast.style.background = "orange";

4. 向元素内添加文本

  • textContent 添加文本(HTML标签也会被当作文本)
  • innerHTML 添加文本,会解析HTML标签
  • outerHTML 替换父节点
  1. <p></p>

使用p.textContent

  1. const p = document.querySelector("p");
  2. //向p标签添加文本
  3. p.textContent = "<b>hahaha</b>";

显示:

使用p.innerHTML

  1. p.innerHTML = "<b>hahaha</b>";

显示:

使用p.outerHTML

  1. p.outerHTML = "<b>hehe</b>";

父节点的p标签没了

5. 获取元素的自定义属性

  • 内置的标准属性,如id,可以直接用querySelector()访问
  • 自定义的属性,通过在属性名前添加data-,然后使用dataset访问
  1. <body>
  2. <div id="a" class="user" name="haha"></div>
  3. <script>
  4. const user = document.querySelector("div");
  5. console.log(user.className);
  6. console.log(user.id);
  7. console.log(user.name);
  8. </script>
  9. </body>

输出:

修改后name为data-name后:

  1. <body>
  2. <div id="a" class="user" data-name="haha"></div>
  3. <script>
  4. const user = document.querySelector("div");
  5. console.log(user.className);
  6. console.log(user.id);
  7. console.log(user.dataset.name);
  8. </script>
  9. </body>

若属性名是多个单词使用-分隔的,如user-age, 获取属性时用驼峰命名法,即userAge获取

  1. <body>
  2. <div id="a" class="user" data-name="haha" data-user-age="6"></div>
  3. <script>
  4. const user = document.querySelector("div");
  5. console.log(user.className);
  6. console.log(user.id);
  7. console.log(user.dataset.name);
  8. console.log(user.dataset.userAge);
  9. </script>
  10. </body>

6. DOM元素增删改查

6.1 创建DOM元素

  • document.createElement()
  1. //创建DOM元素
  2. let div = document.createElement("div");
  3. console.log(div);
  4. let span = document.createElement("span");
  5. span.textContent = "Hey";
  6. console.log(span);

6.2 添加,克隆元素

  • 同一个元素只能被添加到一个位置
  • 如果向不移动原来的元素,使用克隆方法

6.2.1 向父元素内的头部/尾部添加

  • append(element)
  • 向父元素内的末尾添加元素或文本,可同时添加多个(参数)
  1. //创建DOM元素
  2. let div = document.createElement("div");
  3. console.log(div);
  4. let span = document.createElement("span");
  5. span.textContent = "Hey";
  6. console.log(span);
  7. //添加到div中
  8. div.append(span, "aaa", "bbb");

向body中添加以显示元素

  1. //向body中添加以显示元素
  2. document.body.append(div);

向body中添加span,div中的span会被剪切,因为只能插入一个位置

  1. document.body.append(span);

  • 使用element.cloneNode(true)使元素复制后被添加
  1. document.body.append(span.cloneNode(true));

  • 使用append()创建ul列表
  1. //用append()创建列表
  2. const ul = document.createElement("ul");
  3. //for...loop
  4. for (let index = 1; index < 6; index++) {
  5. const element = document.createElement("li");
  6. element.textContent = `li${index}`;
  7. element.style.color = "blue";
  8. element.style.listStyle = "none";
  9. ul.append(element);
  10. }
  11. document.body.append(ul);

  • prepend(element)
  • 向父元素内的头部添加元素或文本,可同时添加多个(参数)
  1. //prepend() 在选定父元素头部添加元素
  2. let title = document.createElement("p");
  3. title.innerHTML = "<b>this is an unordered list created via javascript</b>";
  4. ul.prepend(title);

6.2.2 向选定参考节点的前后添加

  • before()
  • after()
  • 在选定 参考节点 的前后添加

选中参考节点

  1. const referNode = document.querySelector("li:nth-of-type(3)");
  2. referNode.style.background = "yellow";

在其之前,之后分别添加一个元素

  1. const referNode = document.querySelector("li:nth-of-type(3)");
  2. referNode.style.background = "yellow";
  3. //before
  4. let new1 = document.createElement("li");
  5. new1.textContent = "new 01 before reference node";
  6. new1.style.background = "lightgrey";
  7. referNode.before(new1);
  8. //after
  9. let new2 = document.createElement("li");
  10. new2.textContent = "new 02 after reference node";
  11. new2.style.background = "skyblue";
  12. referNode.after(new2);

6.3 替换元素

  • replaceWith() 替换节点
  1. let a = document.createElement("a");
  2. a.textContent = "PHP.cn (This was item3)";
  3. a.href = "https://php.cn";
  4. referNode.replaceWith(a);

6.4 删除元素

  • remove()删除节点
  1. ul.querySelector("ul>li:last-of-type").remove();

6.5 插入元素

  • insertAdjacentElement(position,element)
  • 向元素的 起始标签/结束标签前/后 添加
  • 插入位置可为:
    • beforebegin
    • afterbegin
    • beforeend
    • afterend
  1. const ul = document.createElement("ul")
  2. ul.style.listStyle = "none";
  3. ul.style.border = "1px solid black"
  4. for (let index = 1; index < 6; index++) {
  5. const element = document.createElement("li");
  6. element.textContent = `item${index}`;
  7. ul.append(element);
  8. }
  9. document.body.append(ul);
  10. //using insertAdjacentElement(position,element)
  11. let p = document.createElement("p");
  12. p.textContent = "insertAdjacentElement-beforebegin"
  13. ul.insertAdjacentElement("beforebegin", p)
  14. let li1 = document.createElement("li");
  15. li1.textContent = "insertAdjacentElement-afterbegin";
  16. ul.insertAdjacentElement("afterbegin", li1);

  • insertAdjacentHTML(position,HTML tags)
  • 直接插入HTML标签及内容,省略createElement()步骤
  1. ul.insertAdjacentHTML("beforeend", "<li>insertAdjacentHTML-beforeend</li>")

  • insertAdjacentText()
  • 只能插入文本
  1. let p2 = document.createElement("p");
  2. ul.insertAdjacentElement("afterend", p2);
  3. p2.insertAdjacentText("beforeend", "insertAdjacentText");

7. CSS样式操作

7.1 行内样式

  • element.style.attribute = “value”;
  1. <body>
  2. <p>Bonjour</p>
  3. <script>
  4. const p = document.querySelector("p");
  5. p.style.textDecoration = "underline";
  6. </script>
  7. </body>

7.2 类样式

  • element.classList.add(className1,className2…)
  1. <head>
  2. <meta charset="UTF-8">
  3. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <title>Document</title>
  6. <style>
  7. .bg-yellow {
  8. background-color: yellow;
  9. }
  10. .bg-yellowgreen {
  11. background-color: yellowgreen;
  12. }
  13. .border {
  14. border: 1px slateblue solid;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <p>Bonjour</p>
  20. <script>
  21. const p = document.querySelector("p");
  22. //1. 行内样式
  23. p.style.textDecoration = "underline";
  24. //2. 类样式
  25. p.classList.add("bg-yellow", "border");
  26. </script>
  27. </body>

  • element.classList.replace()
  • element.classList.remove()
  1. p.classList.add("bg-yellow", "border");
  2. p.classList.remove("border");
  3. p.classList.replace("bg-yellow", "bg-yellowgreen");

  • element.classList.toggle()
  • 相当于一个类样式的开关,有则关闭,无则打开
  1. p.classList.add("bg-yellow", "border");
  2. p.classList.remove("border");
  3. p.classList.replace("bg-yellow", "bg-yellowgreen");
  4. p.classList.toggle("border");

7.3 计算样式 (只可读取)

  1. let styles = window.getComputedStyle(p, null);
  2. console.log(styles.getPropertyValue("height"));
  3. console.log(styles.getPropertyValue("color"));
  4. console.log(styles.getPropertyValue("background-color"));
  5. //也可用
  6. let sts = document.defaultView.getComputedStyle(p, null);
  7. console.log(sts.getPropertyValue("color"));

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments