DOM学习实用路线(4)——DOM属性操作及ECMA、DOM 的属性操作的区别

DOM 属性操作



注意 . 和 [] 都是 ECMAScript 中,对象的属性操作,对象属性的值会被存在内存中, 想要直接获取存在 文档中属性,或者 想把一个属性设置在文档中我们需要使用DOM 的属性操作:

  • el.attributes 元素所有属性的集合
  • el.getAttribute(“attr”) 获取属性
  • el.setAttribute(“attr”,“val”) 设置属性
  • el.removeAttribute(“attr”) 移出属性
  • el.hasAttribute(“attr”) 判断是否有这个属性
  • 只要操作了innerHTML 元素的所有子元素上,存在内存中的事件和相关的属性都会丢失。如果希望元素的某些属性在操作了父级的innerHTML 之后,还存在就把这个属性加在 DOM 中。
<!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="box" class="cbox" custom='DOM'>div标签</div>
<script>
    {
        let box = document.querySelector("#box");
        console.log(box.id);
        console.log(box.tagName);
        console.log(box.className);
        console.log(box.custom);
    }
</script>
</body>
</html>

  注意:元素对象下的“class”被规定为“className”。
  合法属性:w3c 规定的元素的属性,都存到这个对象中。
  因此,这里“custom”自定义属性是获取不到的,也即它属性不合法属性。
在这里插入图片描述


el.attributes 元素所有属性的集合
el.getAttribute(“attr”) 获取属性

let box = document.querySelector("#box");
console.log(box.attributes);
console.log(box.getAttribute("custom"));
console.log(box.getAttribute("class"));

  可能就有小小白问了,已经有了“.”,“[ ]”两种属性操作了,干嘛还需要getAttribute呢?
  这里很明显看出它可以获取自定义属性,而我们通常用的属性操作获取不了!

在这里插入图片描述


  el.setAttribute(“attr”,“val”) 设置属性
  el.removeAttribute(“attr”) 移出属性
  el.hasAttribute(“attr”) 判断是否有这个属性

let box = document.querySelector("#box");
console.log(box.setAttribute("Attribute1","自定义属性1"));
console.log(box.removeAttribute("class"));
console.log(box.hasAttribute("class"));
console.log(box.hasAttribute("Attribute1"));

在这里插入图片描述


溜_x_i_a_o_迪童鞋认为ECMA和DOM属性操作区别是一个容易被忽略的知识点,因为目前很多公司不允许用DOM,但小编还是希望能把知识理解透彻,如果有分析不到位的地方,还请大牛指出!!!
ECMA 的属性操作:操作的是对象,具体的数据存在内存中,可以存储各种类型数据;
DOM 的属性操作:值是存在文档中,类型只能是字符串,不是字符串的话,也会被转成字符串。
属性操作区别:ECMA 的属性操作存在内存中,DOM 的属性操作存在文档中。但内存中可以存任何类型,存对象都行,可是文档中只能存字符串。
“console.log(box.SixXD);”:ECMA是从内存中获取,而这里DOM属性操作是放在文档中的,因此在内存中是找不到SixXD属性的!!
“console.log(box.getAttribute(“index”));”:index属性同理它是存在内存中的,文档中没有,因此DOM属性操作获取不了。

let box = document.querySelector("#box");
box.index = 0; // ECMA 的属性操作,操作的是对象,具体的数据存在内存中,可以存储各种类型数据
box.setAttribute("SixXD",666);// DOM 的属性操作,值是存在文档中,类型只能是字符串,不是字符串的话,也会被转成字符串
console.log(typeof box.index);
console.log(typeof box.getAttribute("6xd"));
console.log(box.SixXD);
console.log(box.getAttribute("index"));

“box.index = 0;”,这里属性操作是在内存中,因此在文档中没有index属性。
在这里插入图片描述

在这里插入图片描述




(后续待补充)

发布了34 篇原创文章 · 获赞 12 · 访问量 2527

猜你喜欢

转载自blog.csdn.net/u013946061/article/details/105409962