Search code examples
javascripthtmlcsshref

How to add new image element to html href link with javascript?


I have a problem creating a new image element to this code here:

<a href="/sound-packs/" data-link-title="Sound Packs">Sound Packs</a>

Unfortunately, I do not have access to the HTML code because it belongs to a locked template of "jimdo". I can only insert CSS codes and javascript in the "head area". Is there a way to add an image element to this HTML code with javascript?


Solution

  • Yes, there is a way to do this using just javascript. Firstly you need to set the window.onload callback to a function. Within this function, you can then get the element you want to add the image to. Here I added the image to the element with the attribute data-link-title which is equal to "Sound Packs".

    Lastly, you can use .innerHTML on this element to add the HTML you want to add within this element. Here I added a <br /> followed by an <img> tag:

    document.body.onload = function() {
      let soundPacks = document.querySelector('[data-link-title="Sound Packs"]');
      soundPacks.innerHTML += "<br /><img src='https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a' alt='StackOverflow Logo'/>";
    }
    <a href="/sound-packs/" data-link-title="Sound Packs">Sound Packs</a>