Reputation: 73
I am Trying to change my logo image source with Java script code. I do not want to add any function but when page loads new image source is reflected on the header of the page.I do not have Id but class name to target change of source image.I am not able to get results nothing happens can you please point me towards right directions.
document.getElementByClassName("logo-img").src= "url";
Upvotes: 0
Views: 1054
Reputation: 469
The method you're using document.getElementByClassName()
should be document.getElementsByClassName()
(elements instead of element). This returns an array of elements with that classname, so in this case you'll have to access the first element of that array. Then you can change the .src
document.getElementsByClassName("logo-img")[0].src = "url"
Upvotes: 1
Reputation: 23654
As mentioned, getElementsByClassName
returns a collection, whereas querySelector gets the first matching item, referenced by the selector, classname or id. Also you can set the src
using setAttribute()
let url = 'new-logo.jpg';
document.querySelector(".logo-img").setAttribute('src', url);
Upvotes: 1
Reputation: 31
document.getElementsByClassName
returns an HTMLCollection of all elements in the document with the specified class name. As this is an array, you have to access the elements by their index. If you only have one element in the document with the specified class you can use document.getElementsByClassName("logo-img")[0].src= "url";
.
Upvotes: 1