JavaScript中property与attribute对属性操作的异同

    科技2022-07-14  136

    属性操作

    1,元素节点的属性(property) 2,html标记的属性(attribute) 3,属性节点

    注:html标记中的属性其实是attribute,而js中节点的属性是property,这2种属性新增属性时并不通用(除非是html标准属性)

    1,属性节点操作属性(property)

    获取节点后,可以直接对节点对象进行js对象的属性操作 增 删(对已有初始值的标准属性无效) 改

    标准属性: id,title,href,style,class(实际为className)等html标记自带的属性,可直接用属性访问的方法访问或赋值

    2,直接访问html标记的属性(attribute)

    增删改操作使用如下方法: getAttribute 得到 dom 属性A.getAttribute(name) setAttribute 设置 dom 的属性A.setAttribute(name,value) hasAttribute 检测属性是否存在A.hasAttribute(name) removeAttribute 删除 dom 属性A.removeAttribute(name)

    Atrribute和property的区别:属性节点和js对象中的属性

    实例

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .myClass{ background-color: red; } body{ font-size: 40px; } .text{ font-size: 40px; } </style> </head> <body> <div id = "myDiv1"> 我在mydiv1中 <p class="myClass" id = "myP1">我在myP1中</p> <ul id = "ul1"> <li class="myClass" id="li1">1</li> <li id = "li2">2</li> <li id = "li3">3</li> </ul> <input type="text" id="myText1"> <a href="http://www.baidu.com" id="myA1">我是链接</a> </div> <script> //--------使用js对象操作属性-------------------------- var text = document.getElementById("myText1"); text.value = "这是js中设置的内容"; text.className = "text";//如果要修改html标记中的类名,不能直接使用class,要用className代替 text.id = "myT"; text.aa = "这是aa属性值";//设置HTML不存在的新属性时,并不会在HTML标记中显示 console.log(text.aa, text.id); delete text.aa; delete text.id;//删除html标记的标准属性是不可以的 console.log(text.aa, text.id); //--------直接对HTML标记中的属性进行操作attribute------------------------- var a = document.getElementById("myA1"); a.setAttribute("href", "http://www.sina.com.cn"); a.setAttribute("aa", "这是aa属性的值"); console.log(a.href);//可以得到使用setAttribute方法修改的值 console.log(a.aa);//不可以得到使用setAttribute方法修改的值,因为aa不是html的标准属性 a.aa = "这是js对象中的值"; console.log(a.aa); // a.removeAttribute("aa"); a.removeAttribute("href");//可以删除html中的标准属性 </script> </body> </html>
    Processed: 0.009, SQL: 8