1.getAttribute
在JavaScript中,我们可以使用getAttribute()方法来获取元素某个属性的值
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script> window.onload=function() { var oBtn=document.getElementById("btn"); oBtn.onclick=function() { alert(oBtn.getAttribute("id")); } } </script> </head> <body> <input id="btn" class="myBtn" type="button" value="获取"/> </body> </html>
2.setAttribute
在JavaScript中,我们可以使用setAttribute()方法来设置元素某个属性的值
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script> window.onload=function() { var oBtn=document.getElementById("btn"); oBtn.onclick=function() { oBtn.setAttribute("value","button"); }; } </script> </head> <body> <input id="btn" type="button" value="修改" /> </body> </html>
3.removeAttribute
在JavaScript中,我们可以使用removeAttribute()方法来删除元素的某个属性
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> .main{color:red;font-weight:bold;} </style> <script> window.onload=function() { var oP=document.getElementsByTagName("p"); oP[0].onclick=function() { oP[0].removeAttribute("class"); }; } </script> </head> <body> <p class="main">你偷走了我的影子,无论你在哪里,我都会一直想着你。</p> </body> </html>
4.hasAttribute
在JavaScript中,我们可以使用hasAttribute()方法来判断元素是否含有某个属性
hasAttribute()方法会返回一个布尔值。如果包含该属性,会返回true;如果不包含该属性,会返回false
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> .main {color: red;font-weight: bold;} </style> <script> window.onload=function() { var oP=document.getElementsByTagName("p"); if(oP[0].hasAttribute("class")) { oP[0].onclick=function() { oP[0].removeAttribute("class"); }; } } </script> </head> <body> <p class="main">你偷走了我的影子,无论你在哪里,我都会一直想着你。</p> </body> </html>