getAttribute
getAttribute是一个函数,它只有一个参数——你打算查询属性的名字。
object.getAttribute(attribute)
getAttribute方法不属于document对象,不能通过document对象调用,只能通过元素节点对象调用。
例如:
var paras=document.getElementsByTagName('p');
for(var i=0;i<paras.length;i++) {
var title_text=paras[i].getAttribute('title')
if(title_text!=null) { //等同于 if(title_text) { alert(title_text) }
alert(title_text) //当检查某项数据是否为null时,其实是在检查它是否存在。如果存在则条件为真,如果不存在,则条件为假。
}
}
setAttribute
object.setAttribute( attribute , value )
setAttribute与getAttribute不同:允许对属性的值进行修改,若节点没有此属性那么它会先创建属性 然后设置它的值。
相同:都只能用于元素节点
var el=document.getElementById('el')
el.setAttribute('title','a good name')
alert(el.getAttribute('title'))
getAttribute和setAttribute综合练习——图片切换效果
<ul>
<li><a href="imgs/food1.jpg" οnclick="showpic(this,'pic');return false;">firework</a></li>
<li><a href="imgs/food2.jpg" οnclick="showpic(this,'pic');return false;">coffee</a></li>
<li><a href="imgs/food3.jpg" οnclick="showpic(this,'pic');return false;">rose</a></li>
<li><a href="imgs/food4.jpg" οnclick="showpic(this,'pic');return false;">big ben</a></li>
</ul>
<div>
<img id="pic" src="imgs/food1.jpg" alt="" width="200" height="200">
</div>
function showpic(whichpic,whichId) {
var pic=document.getElementById(whichId);
var attr=whichpic.getAttribute('href')
pic.setAttribute('src',attr)
}
childNodes
childNodes属性用来获取一个元素上的所有子元素,是一个包含这个元素全部子元素的数组————
返回的数组包含所有类型的节点,而不仅仅是元素节点。事实上,文档里每一样东西都是一个节点,甚至连空格和换行符都被解释为节点,而它们也包含在childNodes属性所返回的数组中
function countBodyChildren() {
var body_el=document.getElementsByTagName('body')[0]
alert(body_el.childNodes.length)
}
window.οnlοad=countBodyChildren
nodeType
每个节点都有nodeType属性
nodeType的值是一个数字
元素节点的nodeType属性值是 1
属性节点的nodeType属性值是 2
文本节点的nodeType属性值是 3
nodeValue
一个节点的值(元素节点的值)
var description=doucment.getElementById('description')
alert(description.childNodes[0].nodeValue)