Pergunta

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

Foi útil?

Solução

getElementsByTagName (plural) returns an array.

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top