您的位置:首页 > Web前端 > JavaScript

Get element by JavaScript

2017-03-23 22:44 148 查看
    There are four functions for us to get the document elements , and all of them are the functions of document : getElementById() , getElementsByClassName() , getElementsByName() , getElementsByTagName() . You can call them using | document.get... | . 

    The getElementsByClassName() , the getElementsByName() and the getElementsByTagName() return a NodeList . AKA , it is a collection , or you can call it a array . And the getElementById() return a element , so it is different . 



    But you might wonder why I bring this up . Not just give you a heads up . And the answer is YES . Because when it return a NodeList , you have to use it with the way we use a array , means we should use it with "[ ]" . And you also should it if there
is just one element in the list . 

    Let me show you . Here is my code : 

<div></div>

<script>
var div = document.getElementsByTagName("div");
console.log(div);
div.setAttribute("class","first");
</script>
    The first class is : 
.first {
width: 100%;
height: 200px;
bottom: 0;
left: 0;
background-color: green;
}


    And run it : 


   

    There is a error ! 

    In the body , there is one div element , and if you get it and set it a class like the way I did , and it will cause a error : Uncaught TypeError: div.setAttribute is not a function . So why . Like I said : getElementsByTagName() returns a NodeList .
So the NodeList type doesn't have a function named getElementsByTagName . So you should code this way : 

<div></div>

<script>
var div = document.getElementsByTagName("div");
console.log(div[0]);
div[0].setAttribute("class","first");
</script>
    Run it : 



    

    And we did it ! No error !

    So , conclusion : you have to use "[ ]" to get the element when you use getElementsByClassName() , getElementsByName() , getElementsByTagName() functions , even there is one element . Actually it is not so confused , because it returns a LIST !!! But getElementById()
don't need , because as you know you only can ID a ONE element in a document . So it returns one element .  Like this : 

<div id="div"></div>

<script>
var idDiv = document.getElementById("div");
idDiv.setAttribute("class","fourth");
</script>
    Hope it helps you , good night . 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: