查询属性值用getAttribute()方法
<body>
读取 <a href="dom_obj_attributes.php" target="_blank">Attr 对象</a>.
<p id="demo">单击按钮以显示上述链接的目标属性的值</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var a=document.getElementsByTagName("a")[0];
document.getElementById("demo").innerHTML=a.getAttribute("target");
}
</script>
点击按钮时,将获取属性target的值:_blank替换掉P标签中的内容。
增加属性值用setAttribute()方法
<input value="OK">
<p id="demo">点击下面的按钮来设置按钮的类型属性。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
document.getElementsByTagName("INPUT")[0].setAttribute("type","button");
};
</script>
点击按钮后,将input的type值设置为button,input输入框就会变为button按钮。
删除元素值用removeAttribute()方法
<h1 style="color:red">Hello World</h1>
<p id="demo">点击下面的按钮删除上面的标题的样式属性</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
document.getElementsByTagName("H1")[0].removeAttribute("style");
};
</script>
点击按钮后,删除h1标签的style属性,字体颜色从红色变为默认黑色。
查询元素值用attributes方法
<p id="demo">单击按钮,查看按钮元素有多少个属性:</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var btn=document.getElementsByTagName("BUTTON")[0];
var x=document.getElementById("demo");
x.innerHTML=btn.attributes.length;
}
</script>
<p>结果应为1(按钮元件的onclick属性)</p>
<p><strong>注意:</strong> 在Internet Explorer 8 或者更早版本中,attributes 属性将返回所有可能元素的集合 ,并将在这个示例中显示一个比1更高的数字。</p>
attributes 属性返回指定节点属性的集合,可以使用 length 属性确定属性的数量,然后你可以遍历所有的属性节点提取你想要的信息。