Search code examples
javascriptjquerygetelementbyidgetelementsbytagname

Why getElementsByTagName()[0] return's but getElementById()[0] return's undefined?


I am trying the following code and getting following results:

console.log(document.getElementsByTagName('a')[0]); //retuns <a id="link" href="http://stackoverflow.com/questions/ask"></a>

console.log($('a')[0]);//retuns <a id="link" href="http://stackoverflow.com/questions/ask"></a>

console.log(document.getElementById('link'));//retuns <a id="link" href="http://stackoverflow.com/questions/ask"></a>

console.log(document.getElementById('link')[0]);// returns undefined 

console.log($('#link')[0]); //retuns <a id="link" href="http://stackoverflow.com/questions/ask"></a>

Can anybody tell why these (console.log(document.getElementById('link')[0]);// returns undefined and console.log($('#link')[0]); //retuns <a id="link" href="http://stackoverflow.com/questions/ask"></a>) behave weirdly?

Demo


Solution

  • getElementsByTagName (plural) returns an array.

    getElementById (singular) returns a single element (or null).