Example:
<input type="text" name="peixe">
How do I get the name fish?
Note: pure javascript
Example:
<input type="text" name="peixe">
How do I get the name fish?
Note: pure javascript
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:
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:
You can also use queryselector
console.log(document.querySelector("input").name)
<input type="text" name="peixe">
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 thequerySelectorAll()
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
...
console.log(document.querySelector('input').name);
<input type="text" name="peixe">