1. 获取元素的方式
布局如下:
<style>
#box{background:red;width:400px;}
#otherID{background:green;}
#box .otherClass{display:none;}
</style>
<div id="box" defined="me" style="background-color:red;">
<ul class="ulClass" style="background-color:green;">
<li class="liClass" style="background-color:yellow;"></li>
<li class="liClass"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
- var boxID = document.getElementById('box');//获取元素Id
- var boxClass = document.getElementsByClassName();//获取class类的标签。boxClass是一个类数组
- var tagLi = boxID.getElementsByTagName('li');//获取id为box下的li。tagLi也是一个类数组。
下面的是通过和css中的样式定位一样来定位节点;
- var selectorLi = document.querySelector('#box ul li');//获取#box ul 中的第一个li节点;
- var selectorAllLi = document.querySelectorAll('#box ul li');//获取#box ul 中的所有li节点;类数组;
注意:上述获取方式只能获取内联样式
如果要获取非内联的样式,比如获取上述div的宽度
getComputedStyle 或 currentStyle
使用方法:
var boxID = document.getElementById('box'); alert(getComputedStyle(box).width) 获得宽度 alert(box.currentStyle.width) 获得宽度
两个都获取样式,但它们的区别是:getComputedStyle对一些低版本IE不支持,currentStyle只兼容IE。
所以一般都会把它俩结合来写
Demo1:
var oBox = document.querySelector('#box'); var w = getStyle( oBox , 'backgroundColor' ); function getStyle( obj , attr ){ if ( obj.currentStyle ) { return obj.currentStyle[attr]; }else { return getComputedStyle(obj)[attr]; } };
兼容性 :上述所有获取方式中:
getElementsByClassName(); 不兼容IE8及以下
其中按js运行机制的分类又分:静态方法 和 动态方法
静态方法:如var boxID = document.getElementById('box');
变量boxID的内容并不会随着所绑定的标签id改变而改变。boxID.id="otherID",并不会改变boxID内容。
var boxID = document.getElementById("box");
alert(boxID.style.backgroundColor);//弹出red
boxID.id = "otherID";
alert(boxID.style.backgroundColor);//弹出red
动态方法:是对节点的动态绑定,随所绑定的属性变化而变化;是类数组
var boxClass = document.getElementsByClassName();
var liClass = document.getElementsByClassName('liClass');
alert(liClass[0].style.backgroundColor);//弹出green
liClass[0].className = "otherClass";
alert(liClass[0].style.backgroundColor);//报错
上诉报错是因为class是动态绑定的,当class变化的时候,变量liClass也会发生变化;
动态绑定的好处是可以根据需要而改变需要的样式;上述class改变后,就可以成功隐藏目标li标签了。
2 自定义标签属性
var boxID = document.getElementById("box");
//获取属性值
var aa = boxID.getAttribute('defined');
alert(aa);//弹出 me
//设置属性值
boxID.setAttribute('defined','you');
其设置值的时候,如果该属性名没有。则添加该属性并设置值
//删除属性
boxID.removeAttribute('defined');
上述对标签属性的操作,一般是用来操作自定义属性。