<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> *{ font-family: 微软雅黑; } </style> </head> <body> <h1 id='hid'>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</h1> <h1 class='hcls'>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</h1> <h1 class='hcls'>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</h1> <h1 class='hcls'>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</h1> <h1 class='hcls'>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</h1> <h1 class='hcls'>aaaaaaaaaaaaaaaaaaaaaaaaaaaa</h1> </body> <script> hidobjs=document.getElementsByClassName('hcls'); //hidobjs是一个对象集合(数组) //hidobjs[0].style.background='#f0f' for(i=0;i<hidobjs.length;i++){ hidobjs[i].style.background='#f0f'; } </script> </html>
getElementsByName通过标签的name属性来获取元素对象
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <style> *{ font-family: 微软雅黑; } </style> </head> <body> <form action=""> <p>用户名:</p> <p><input type="text" name='username'></p> <p>密码:</p> <p><input type="text" name='password'></p> <p><input type="submit" value="Ok"></p> </form> </body> <script> usernameobj=document.getElementsByName('username'); usernameobj[0].onfocus=function(){ this.style.outlineColor='#f00'; } </script> </html>