Reputation: 71
I am trying to set an element's ID by it's name for a loop.
I have Tried to set the Id by calling the element by it's name then setting the id as a string
<img name="myFirstImage" src="" id="" style="width:100%;cursor:pointer"
<script> document.getElementsByName("myFirstImage").id = "imageBox";</script>
Please note that I set the img scr to an img by its ID in a loop, so the img displays if I set the image ID manually. The problem is setting the ID by the name of the element. Everything else works.
Upvotes: 0
Views: 59
Reputation: 36574
document.getElementsByName()
returns a NodeList. You are trying to change the id of NodeList.
You can also you document.querySelector('img[name="myFirstImage"]')
. This will return single element.
document.getElementsByName("myFirstImage")[0].id = "imageBox";
console.log(document.getElementById('imageBox'));
<img name="myFirstImage" src="" id="" style="width:100%;cursor:pointer"/>
Upvotes: 0
Reputation: 68933
Document.getElementsByName()
returns collection. To access the element you have use proper index.
The
Document.getElementsByName()
method of the Document object returns a NodeList Collection of elements with a given name in the document.
document.getElementsByName("myFirstImage")[0].id = "imageBox";
console.log(document.getElementsByName("myFirstImage")[0].id);
<img name="myFirstImage" src="/test" id="" style="width:100%;cursor:pointer">
Upvotes: 1