How do I get the name of an input

3

Example:

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

How do I get the name fish?

Note: pure javascript

    
asked by anonymous 19.12.2017 / 19:00

3 answers

7

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

var nomes = document.getElementsByTagName("input");
console.log(nomes[0].name);
<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:

console.log(document.querySelector('input').name);
<input type="text" name="peixe"> 

and the supported browsers are:

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

19.12.2017 / 19:03
2

You can also use

console.log(document.querySelector("input").name)
<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.

    
19.12.2017 / 19:07
1

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

console.log(document.querySelector('input').name);
<input type="text" name="peixe"> 
    
19.12.2017 / 19:09