div.appendChild().appendChild()

Mike Gifford picture Mike Gifford · Apr 5, 2012 · Viewed 8.2k times · Source

Logically, I want to embed an image in a link in a div. I've successfully done this with either the link or the image. I've even done it with the link and image in parallel (which is useless) for my purposes. But can't seem to have the image wrapped in a link inside a div.

var div = OpenLayers.Util.createDiv();
var img = OpenLayers.Util.createImage(null, null, null, null, null, null, null, delayDisplay);
img.className = "olAlphaImg";
img.alt = altText;

var link = document.createElement("a");
// link.setAttribute("href", "#");
link.href="#" + altText;
link.appendChild(img);

div.appendChild(link); 

OpenLayers.Util.modifyAlphaImageDiv(div, id, px, sz, imgURL, position, border, sizing, opacity, altText);

return div;

This is for an OpenLayers where I'm trying to ensure keyboard navigation. I just am not sure how to do this with javascript and all the examples only use one appendChild reference. I've tried with innerHTML() but I wasn't using strings so that didn't seem useful.

Answer

Oleg picture Oleg · Apr 5, 2012

What do you mean by

can't seem to have the image wrapped in a link inside a div

Do you experience any errors?

I might have misunderstood your question, but if not, your code should work.

Here's my example: a working jsfiddle that wraps an image into a link into some container.

var img = document.createElement('img');
img.src = 'https://www.google.fr/images/srpr/logo3w.png';

var anchor = document.createElement('a');
anchor.href = 'http://google.com';

// Wrap image in the link (anchor):
anchor.appendChild(img);
// Insert the anchor into container:
document.getElementById('container').appendChild(anchor);