天天看点

js中DOM的自定义属性

js中DOM的自定义属性方法有:

1、设置自定义属性:setAttribute

2、获取自定义属性:getAttribute

3、移出自定义属性:removeAttribute

下面就来看一下它们的具体使用方法

<!doctype html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<input type="text" class="inp" id="inp" value="123" abc="abc"/>
<script>
    //获取对象
    var txt = document.getElementById("inp");
//    console.log(txt.abc);//JS通过.的方式不能获取自定义的属性
//   1、 但是可以通过getattribute可以获取到
    console.log(txt.getAttribute("abc"));
    console.log(txt.getAttribute("id"));
    console.log(txt.getAttribute("class"));
    console.log(txt.getAttribute("value"));
//    显示结果依次为:abc   inp   inp  123

//    2、setattribute设置自定义属性,可以在浏览器中通过开发人员工具可以查看属性以及设置到input标签上
    txt.setAttribute("userName","inp");

//    3、removeAttribute移除自定义属性,同样在开发人员工具可以查看属性abc已经被移除掉了
    txt.removeAttribute("abc");
</script>
</body>
</html>
           
js中DOM的自定义属性
js中DOM的自定义属性

注意:通过setAttribute来设置的自定义属性,只能通过getAttribute来获得,不能通过对象.的方式来获得。