getElementsByClassName通過類名獲取元素物件集合
阿新 • • 發佈:2020-12-28
<!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>