Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between getelementsbytagname and getelementsbyname in javascript

Tags:

javascript

I recently came across these two methods for dom elements retrieval in a douglas crockford presentation but couldn't understand the difference between these two.

document.getElementsByTagName()

document.getElementsByName()

can someone please explain it to me.

the link to the video is http://www.youtube.com/watch?v=Fv9qT9joc0M

like image 751
Nav Avatar asked May 21 '13 07:05

Nav


2 Answers

Suppose you have this HTML :

<input name="test" class="cssclassname">

You'd got it with

document.getElementsByTagName('input')

or

document.getElementsByName('test')

or

document.getElementsByClassName('cssclassname')

Also, you can call getElementsByTagName on elements other than document. For example the following is allowed,

document.getElementsById('foo').getElementsByTagName('bar')

But getElementsByName can only be called on document.

Notes :

  • JavaScript is case sensitive, you can't write the functions like you did in your question
  • those functions don't return just the element but a live nodeList, so you'll have to iterate over the result or take the first one if you're sure it's good : document.getElementsByTagName('input')[0]
  • the MDN is a good documentation for JavaScript methods. You should read getElementsByTagName and getElementsByName.
like image 138
Denys Séguret Avatar answered Oct 07 '22 16:10

Denys Séguret


<div name="alpha"></div>
<div name="beta"></div>

var divs = document.getElementsByTagName("div");  // Selects both divs.
var alpha = document.GetElementsByName("alpha");   // Selects the first div.
var beta = document.GetElementsByName("beta");     // Selects the second div.
like image 36
Sani Singh Huttunen Avatar answered Oct 07 '22 16:10

Sani Singh Huttunen