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?
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?
Share Improve this question edited Jun 18, 2018 at 5:20 Osi asked Jun 18, 2018 at 5:03 OsiOsi 1 3 |2 Answers
Reset to default 12With 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"/>
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 name
s.
name
attribute", hence there's alsodocument.getElementsByName()
;) – Andreas Commented Jun 18, 2018 at 5:07getElementsByName
,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 Commented Jun 18, 2018 at 5:16