Get element by JavaScript

    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 . 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值