Min Kyung Kwon
Min Kyung Kwon

Reputation: 173

(javaScript: DOM) setAttribute index

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

Answers (1)

user13637316
user13637316

Reputation:

Because document.querySelectorAll returns an element list.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll


FYI

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

Related Questions