freckles.karin freckles.karin - 1 year ago 42
HTML Question

Add a linked image to html body with javascript

I am trying to add a linked image with JavaScript to the HTML body. The image is displayed, but it's not opening any link (the

event is not triggered).

The reason I'm not just adding the
attribute is, because I want to show different linked images for different scenarios.

My HTML code:

<div id="mypic">
<img src=""

My JavaScript code:

var lang="en";
var survey = document.createElement('survey');
var image = document.getElementById('mypic').getElementsByTagName('img')[0];
var b = survey.appendChild(image);

Answer Source

In your code you say:

var survey = document.createElement('survey');
  • Inside the .createElement() method you have to insert a node. You face a problem, because survey is not a valid node and will no be considered as one in any of the HTML versions released to date.

  • To fix it, insert an anchor node inside .createElement().

Your code should be:

var survey = document.createElement('a');


  • Adding the href attribute is a no brainer. That's what prompts the web browser to navigate to the given link.
  • In order to display a different image based on different scenarios, you just have to replace the given link with some other.

For example:

var link = ((scenario 1) ? "..." : ((scenario 2) ? "..." : "..."));
survey.href = link;