JS DOM编程艺术——setAttribute—— JS学习笔记2015-7-7(第78天)

getAttribute & setAttribute 获取和设置属性

getAttribute 获取属性:

语法:object.getAttribute(attribute);   这个方法不属于document对象,所以不能使用document对象调用,只能通过元素节点对象调用;后面的setAttribute也是这样;

比如;var paras = document.getElementsByTagName('p');

        alert(paras[0].getAttribute('title'))

setAttribute 修改属性;

object.setAttribute(attribute,value);

实例:var shopping = document.getElementById('purchases');

        shopping.setAttribute('title',"a list of goods");

tips:属性也就是包括title、alt、class、id等这些类别,所以可以通过上面这2个方法来获取和设置页面中元素的相应属性,比如改变样式等;

原文地址:https://www.cnblogs.com/zhangxg/p/4628706.html