How do I get the name of an input

Asked

Viewed 717 times

3

Example:

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

How I get the name fish???

Observing: pure javascript

  • What exactly do you want? your screen will only get this input? if yes

  • Do you want to get "fish"? So, if the input had another name, would you get that other name? Or you want to get the input value from the name fish?

  • AKU and managed to resolve?

3 answers

7

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

var nomes = document.getElementsByTagName("input");
console.log(nomes[0].name);
<input type="text" name="peixe"> 

because, it is more supported by browsers:

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

Note: the getelementsbytagname() in this specific case it takes all the elements input, namely, a array of information, in the case of the question only has 1 then nomes[0].name returns the name of this input, if you have 30 input will return a array of those 30. Maybe it lacks a better context, but, the way it is in the question this is what it needs.


There’s another way that’s with querySelector, example:

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

and supported browsers are:

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

Reference:

  • It would be interesting to use this answer as a reference because it has an almost native support, but in relation to simplicity could be edited ;)

  • I don’t get it @Felipeduarte?

  • 1

    Not the simplest way, but the most recommended way...

  • 1

    @Felipeduarte really already edited

2

You can also use

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

Definition and Use

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

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

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

1

I believe the simplest way would be with querySelector, for various elements could use the querySelectorAll...

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.