Reputation: 173
I'm trying to add an image inside <img>
through javaScript DOM and just wondering why the first code works but second code doesn't work? Why does img
need an index?
var img = document.querySelectorAll("img");
img[0].setAttribute("src", "images/image_1.jpg");
img[0].setAttribute("style", "width:500px; height:200px;");
var img = document.querySelectorAll("img");
img.setAttribute("src", "images/image_1.jpg");
img.setAttribute("style", "width:500px; height:200px;");
Upvotes: 0
Views: 410
Reputation:
Because document.querySelectorAll
returns an element list.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
If you use document.querySelector
instead, you don't need to specify the index because it returns the first element within the document that matches the specified selector.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Upvotes: 3