How do I get the name of an input

Posted on

Question :


<input type="text" name="peixe"> 

How do I get the name fish?

Note: pure javascript


Answer :

The most recommended way to get the name would be getElementsByTagName () , example :

var nomes = document.getElementsByTagName("input");
<input type="text" name="peixe"> 

Because, it is most supported by browsers:

  • Google Chrome 1
  • IE 6
  • Firefox 3
  • Safari 3
  • Opera 5

Note: getElementsByTagName () in this case in particular takes all elements input , that is, a array of information, in case the question only has 1 then nomes[0].name returns the name of that input , if it has 30 input will return a array of these 30. Maybe there is a better context, but, as it is in the question, this is what you need.

There’s another way with querySelector , example:

<input type="text" name="peixe"> 

and the supported browsers are:

  • Google Chrome 1
  • Firefox 3.5
  • IE 8
  • Opera 10
  • Safari 3.2

You can also use

<input type="text" name="peixe">

Definition and Use

The querySelector() method returns the first element that matches a CSS selector specified in the document.


Note : The querySelector() method only returns the first element that matches the specified selectors. To return all matches, use the querySelectorAll() method.

If the selector matches an ID in the document that is used multiple times (Note that an “id” must be unique within a page and should not be used more than once) returns the first corresponding element.


I think the simplest way would be with querySelector , for multiple elements could use querySelectorAll

<input type="text" name="peixe"> 


Leave a Reply

Your email address will not be published. Required fields are marked *