最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vanilla JS: How to target an input element by the input-field's name ("name" in DOM tree)

programmeradmin1浏览0评论

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
  • 1 "which of course deals with the HTML element's name and not with a name attribute", hence there's also document.getElementsByName() ;) – Andreas Commented Jun 18, 2018 at 5:07
  • 1 Possible duplicate of JavaScript get element by name – Rajesh Commented Jun 18, 2018 at 5: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 Commented Jun 18, 2018 at 5:16
Add a comment  | 

2 Answers 2

Reset to default 12

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"/>

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论