JS操作DOM元素属性
元素属性:
1.行内标准样式
2.行内自定义属性
3.行外属性
4.点语法动态添加的属性
操作元素属性方法
点语法、字符串语法操作元素
注意点:
1.只能获取行内属性,不能获取行外属性
2.获取到的是带单位的字符串
3.属性既可以获取,也可以修改
4.获取类名使用className,不能使用class,因为class是关键字
类名属性设置:
直接赋值会覆盖原本的样式
<div id="box" class="one"></div>
var box=document.getElementById("box");
box.className="two";
如果要多个样式 使用字符串连接符(使用的时候要注意 要加一个空格,否则会变成一个字符串)
box.className += " two";
点语法获取元素的特点
1.可以获取标准属性
2.可以获取点语法动态添加的属性
console.log(box.aaa);
3.无法获取行内自定义属性
console.log(h1.www);//undefined
4.无法获取行外属性
console.log(box.style.height);//空字符串
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
#box{
background-color: aqua;
height: 100px;
}
.one{
color: blue;
}
.two{
margin: 30px;
}
</style>
</head>
<body>
<div id="box" class="one" style="width: 100px; background-color: antiquewhite;">
我是div
</div>
<h1 id="h1" www="sss">我是标题标签</h1>
</body>
//修改div背景颜色
//1.获取元素
var box=document.getElementById("box");
//获取对象属性
console.log(box.id);
console.log(box["id"]);
console.log(box.className);
console.log(box.style);
console.log(box.style.width);