通过id、classname以及tagname,利用document的getElementById、getElementsByClassName、getElementsByTagName,我们可以获取到文档树中的任意元素节点对象。有了节点对象,我们可能会对其属性进行查看或者修改。本文总结了JavaScript获取和设置对象属性的方法。
1. 获取属性
getAttribute
输入:属性的名字,字符串
输出:属性的值
注:getAttribute是元素节点对象的方法,不是document对象的方法
<script>
var obj = document.getElementById("header");//获取节点对象
var attr = obj.getAttribute("title");//获取title属性
console.log("the title of header:"+attr);
</script>
//结果
2. 设置属性
setAttribute
输入:属性的名字,字符串
输出:无
注:setAttribute同getAttribute一样,是元素节点对象的方法,不是document对象的方法,不能用document调用
var obj = document.getElementById("header");
var attr = obj.getAttribute("title");
console.log("the title of header before change:"+attr);
obj.setAttribute("title","the title has been changed");
console.log("the title of header after change:"+obj.getAttribute("title"));
//结果
以上测试代码对应的HTML代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getAttribute</title>
<style type="text/css">
#header{
width:400px;
height:300px;
}
</style>
</head>
<body>
<div id="container">
<div id="header" title="this is the header">
</div>
</div>
</body>
<script>
//...
</script>
</html>