javascript - explanation of zero index in getElementByTagname method -
i trying use getelemenstbytagname method access array elements.i have searched internet , found of uses.i have seen without [0] @ end of tagname method not work.say
in code if use
var c=document.getelementsbytagname("p");
it doesn't work.rather have use
var c=document.getelementsbytagname("p")[0];
what [0] index means , why used??
full code :
<html> <head> <style> *{margin:0px;padding:0px;} </style> </head> <body> <script> var j=2; var temp; var arr=["favourite","fruit","is","mango","orange","apple"]; for(i=0;i<3;i++){ document.body.innerhtml+=arr[i]+" "; } setinterval(function (){ j++; var c=document.getelementsbytagname("p")[0]; c.style.color="blue"; c.innerhtml=arr[j]+" "; if(j==5){j=2;} },2000); </script> <p style="position:absolute;float:right;top:0px;left:97px;border:0px solid black;width:60px;height:50px;"></p> </body> </html>
document.getelementsbytagname('tag-name')
returns array of html elements (htmlcollection)
so var foo = document.getelementsbytagname('tag-name')
htmlcollection (can thought of array of html elements)
therefore, foo[0]
or document.getelementsbytagname('tag-name')[0]
contains first item in array, i.e., first element matches tagname!
lean more getelementsbytagname()
: https://developer.mozilla.org/en-us/docs/web/api/element.getelementsbytagname
if have many elements on webpage, might use concept of ids
access elements. example, consider html excerpt
<p id="toppara">....</p> <p id="midpara">....</p> <p id="bottompara">....</p>
now access individual elements use:
var foo = document.getelementbyid('toppara');
which return element has id toppara in foo
can use methods related element foo.methodname()
Comments
Post a Comment