Dynamically setting image source with JavaScript function

Hey everyone, I’m trying to figure out how to use a JavaScript function to set an image’s src attribute. Here’s what I’ve got so far:

function getLogoPath() {
    return 'assets/images/logo.png';
}

I want to use this function directly in my HTML, kind of like this (I know this won’t work, but it’s the idea I’m going for):

<img class="logo" src="<script>getLogoPath()</script>" alt="Company Logo">

The goal is to have it render in the browser like this:

<img class="logo" src="assets/images/logo.png" alt="Company Logo">

Is there a way to make this happen? What’s the best method to achieve this? Thanks for any help!

hey mate, i’ve got another idea for ya. why not try using a data attribute? like this:

Company Logo

then use javascript to grab all imgs with data-src and set their src. it’s pretty flexible and keeps ur html clean. just a thought!

The previous answer provides a good solution, but an alternative method might offer more flexibility. Instead of embedding a function call directly in the HTML, you can assign a custom data attribute to your image element with a value that represents your function name. After the page loads, JavaScript can target images using this attribute, retrieve the function name, invoke the function from the global scope, and then update the src attribute with the returned value.

This approach helps keep your HTML clean and separates your markup from your logic, which is particularly useful if you need to handle multiple images.

I’ve actually tackled a similar issue in one of my projects. Instead of trying to use JavaScript directly in the HTML src attribute, which won’t work as you’ve discovered, I’d recommend using JavaScript to set the src after the page loads.

Here’s what worked for me:

  1. Give your img tag an id:
    Company Logo

  2. Then use JavaScript to set the src:
    document.addEventListener(‘DOMContentLoaded’, function() {
    document.getElementById(‘companyLogo’).src = getLogoPath();
    });

This approach lets you keep your getLogoPath() function and dynamically set the image source once the DOM is ready. It’s clean, efficient, and avoids mixing JavaScript directly into your HTML attributes.

Hope this helps solve your problem!