简体   繁体   English

将id添加到输入

[英]Add id to input

I have this input: <input type="text" name="1"> . 我有以下输入: <input type="text" name="1">

Using vanilla JS how can I assign an id to it? 如何使用香草JS为其分配ID? To make it look like this: <input type="text" name="1" id="2"> . 要使其看起来像这样: <input type="text" name="1" id="2">

Have this so far, does not work, and I cannot find out why... 到目前为止,这行不通,我无法找出原因...

var xyz = document.getElementsByName(1");
xyz.setAttribute("id", "2");

getElementsByName returns array. getElementsByName返回数组。 You need set attribute to single element. 您需要将属性设置为单个元素。 Hack: xyz[0].setAttribute... 骇客: xyz[0].setAttribute...

As VeroLom said, 正如VeroLom所说,

getElementsByName returns array. getElementsByName返回数组。

So you have to return only one element : 因此,您只需要返回一个元素:

var xyz = document.getElementsByName(1")[0]; // there, I pick the first element of the array
xyz.setAttribute("id", "2");
var xyz = document.getElementsByName("myName");
xyz[0].id = "myId";

or 要么

xyz[0].setAttribute("id", "myId");

Please notice that IDs and names can't start wit a number . 请注意, ID和名称不能以数字开头

They function .getElementsByName(1) returns an array of HTML DOM object with the name 1. 它们的函数.getElementsByName(1)返回名称为1的HTML DOM对象数组。

To access the first element try this: 要访问第一个元素,请尝试以下操作:

xyz = document.getElementsByName("1")[0];
xyz.setAttribute("id", "2");

and by the way, ID's should start with a letter. 顺便说一下,ID应该以字母开头。

var xyz = document.getElementsByName(1");
xyz.setAttribute("id", "2");

This gives you an array of elements by name "1". 这将为您提供名称为“ 1”的元素数组。 So you need to traverse and give id to each element. 因此,您需要遍历并为每个元素赋予id。

So, if you are sure you have only one element with this name you can do 因此,如果您确定只有一个具有此名称的元素,则可以

 var xyz = document.getElementsByName("1")[0];
 xyz.setAttribute("id", "2");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM