parag
parag

Reputation: 21

how to use javascript to add link to image element created using javascript

how to add link for the image created using following javascript.

thanks for any help or replies.

for(var i=0; i<images.length; i++) {
   var t = document.createElement('IMG');
   t.setAttribute('src',images[i]);
   t.setAttribute('border', 0);
   t.setAttribute('width',imageWidth);
   t.setAttribute('height',imageHeight);
   t.style.position = 'absolute';
   t.style.visibility = 'hidden';

   el.appendChild(t);
}

Upvotes: 2

Views: 13844

Answers (3)

phpNutt
phpNutt

Reputation: 1539

You need to first create a anchor element then append the img element to it... like so:

for(var i=0; i<images.length; i++) {
   var a = document.createElement('a');
   a.href = "http://www.MYWEBSITE.com/"
   var t = document.createElement('IMG');
   t.setAttribute('src',images[i]);
   t.setAttribute('border', 0);
   t.setAttribute('width',imageWidth);
   t.setAttribute('height',imageHeight);
   t.style.position = 'absolute';
   t.style.visibility = 'hidden';
   a.appendChild(t);
   el.appendChild(a);
}

Then append the anchor to 'el'

Matt

Upvotes: 1

Quentin
Quentin

Reputation: 943193

Create an a element in the same fashion. Append it to el instead of the image and append the image to it.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382666

Try this:

for(var i=0; i<images.length; i++) 
{

   var t = document.createElement('IMG');
   var link = document.createElement('a'); // create the link
   link.setAttribute('href', 'www.example.com'); // set link path
   // link.href = "www.example.com"; //can be done this way too

   t.setAttribute('src',images[i]);
   t.setAttribute('border', 0);
   t.setAttribute('width',imageWidth);
   t.setAttribute('height',imageHeight);
   t.style.position = 'absolute';
   t.style.visibility = 'hidden';

   link.appendChild(t); // append to link
   el.appendChild(link);
}

Upvotes: 5

Related Questions