Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put image in anchor tag dynamically using javascript

I have dynamically created image in javascript. I want img to be placed inside an anchor tag how can i do this?

        var element = document.createElement("img");
        element = cell.appendChild(element);
        element.setAttribute("src", "/Images/Delete.gif");
like image 507
Ulhas Tuscano Avatar asked May 09 '11 10:05

Ulhas Tuscano


People also ask

How do I add an image to an anchor tag?

To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image. With that, also add the height and width.

How do I create a dynamic image in HTML?

Step 1: You need to create an empty IMG element by using this method, document. createElement(). Step 2: In the next step, you need to set its different attributes like (height, width, src, alt, title, etc). Step 3: Now lastly under the final step, you need to insert this into the HTML document.

Can anchor tag have image?

We can even have multiple images or images and text or images with spans and text. Anchor elements, as well as img and span elements are inline by default. If we wrap an image with an anchor element, the image becomes the anchor target. We can click the image anywhere and the link will work.


1 Answers

var anchor=document.createElement('a');
anchor.href='#';
var element = document.createElement("img");
element.setAttribute("src", "/Images/Delete.gif");
anchor.appendChild(element);
cell.appendChild(anchor);

i did not test the code, i used my brain as interpreter, so there may be an error in it. but i think you should get the concept.

like image 67
lawl0r Avatar answered Oct 15 '22 11:10

lawl0r