Reputation: 109
I have input type text
<input type="text" name="processName">
I want to set new id to this input element using name of the input element
document.getElementsByTagName("processName")[0].setAttribute("id", "proceesOffsetId");
Which is not working
Upvotes: 0
Views: 1488
Reputation: 2301
So getElementsByTagName
refers to the element tag (for example: div tag, li tag, input tag, etc...). It doesn't fetch elements via the name
attribute.
So in your case, to target that input
element, you could do something like this:
document.getElementsByTagName("input")[0].setAttribute("id", "proceesOffsetId");
This will give the input
element an id
of proceesOffsetId
.
Alternatively, to target the name
attribute, you could use document.getElementsByName
:
document.getElementsByName("processName")[0].setAttribute("id", "proceesOffsetId");
This will also give the input
element an id
of proceesOffsetId
.
Upvotes: 3
Reputation: 472
Instead of using getElementsByTagName, use getElementsByName which is appropriate as per your requiement.
HTML :
<input type="text" name="processName">
JS:
var x= document.getElementsByName("processName");
console.log(x);
x[0].setAttribute("id", "proceesOffsetId");
Here's the reference : https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
Upvotes: 0
Reputation: 4370
you should use getElementsByName
document.getElementsByName("processName")[0].id = "proceesOffsetId";
Upvotes: 3