getElementsByClassName通過類名獲取元素對象集合


<!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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM