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");
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With