3

How to target an input element by the input-field's name ("name" in DOM tree), in vanilla JavaScript (ES6 or later)?

I ought to do it with document.querySelector(''). I didn't find a way. I only found the older getElementsByTagName which per my understanding deals with the HTML element's name and not with a name attribute of (usually) an input element itself.

Is it possible in ES6 without jQuery?

Osi
  • 1
  • 3
  • 9
  • 30
  • 1
    _"which of course deals with the HTML element's name and not with a `name` attribute"_, hence there's also [`document.getElementsByName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName) ;) – Andreas Jun 18 '18 at 05:07
  • 1
    Possible duplicate of [JavaScript get element by name](https://stackoverflow.com/questions/10306129/javascript-get-element-by-name) – Rajesh Jun 18 '18 at 05:13
  • While you can use `getElementsByName`, `querySelector` seems a bit more appropriate here because you want to select only a single element, rather than generate a collection and proceed to select the first item in the collection. – CertainPerformance Jun 18 '18 at 05:16

2 Answers2

9

With querySelector you can use any CSS selector. In your case you need to do an Attribute Selector.

const one = document.querySelector("input[name=one]");
const two = document.querySelector("input[name=two]");

console.log(one);
console.log(two);
<input name="one"/>
<input name="two"/>
Jorjon
  • 5,316
  • 1
  • 41
  • 58
  • Over SO, you earn privileges with rep. Please use them. This is a very basic query which can be solved with googling. Please choose to close such posts as duplicate instead. It will help more. – Rajesh Jun 18 '18 at 05:15
7

Yes, you can do it with querySelector:

console.log(
  document.querySelector('input[name="inputname"]').value
);
<input name="inputname" value="foo">

No ES6 support required.

You can do the same sort of thing when you want to select an element with any other attribute, not just names.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Please choose to close such posts as duplicate instead. – Rajesh Jun 18 '18 at 05:13
  • @Rajesh The duplicate has no example using `.querySelector()` which is what TO has asked for (kind of...). – Andreas Jun 18 '18 at 05:16
  • Ok, let me share another link with `querySelector` in answer. But the point was, you should look for dupes instead of answering. This will only make content redundant. A user with your rep should know this. – Rajesh Jun 18 '18 at 05:17
  • @CertainPerformance Another possible duplicate with `.querySelector` in mentioned approached: https://stackoverflow.com/questions/15148659/how-can-i-use-queryselector-on-to-pick-an-input-element-by-name – Rajesh Jun 18 '18 at 05:22