setAttribute("属性名","属性值");修改属性
例:
<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title><script> ???function dj(){ ???????var sx = document.getElementById("a"); ???????sx.setAttribute("class","bb"); ???}</script><style> ???.aa{ ???????width: 100px; ???????height: 100px; ???????background-color: blue; ???} ???.bb{ ???????width: 200px; ???????height: 200px; ???????background-color: red; ???}</style></head><body><div id="a" onClick="dj()" class="aa"></div></body></html>
是把原来div里面的样式aa变成了bb
getAttribute("属性名");是获取标签
removeAttribute("属性名"); 是删除标签
操作样式
元素.style.样式 = " ";
也就是更改元素里面的样式。
创建元素 document.createElement(标签名);
追加元素 元素对象.appendChild(元素对象);
删除元素 元素对象.remove();
<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title><script> ???function createEL(){ ???????var div = document.createElement("div"); ???????div.setAttribute("id","dd"); ???????div.style.width = "100px"; ???????div.style.height = "100px"; ???????div.style.backgroundColor = "red"; ???????div.innerHTML = "ggg"; ???????//追加元素 ???????var objDiv = document.getElementById("dd"); ???????objDiv.appendChild(div); ???????//把自己删除 ???????obj.remove(); ???}</script></head><body><button onClick="createEL()">创建</button></body></html>
JS操作元素属性(转)
原文地址:http://www.cnblogs.com/wangyufei123/p/7746127.html