How to use HTML img element In Javascript

To include an SVG file in an HTML document using the img element, you can set the src attribute of the img tag to the path of the SVG file.

Syntax:

 <img src='logo.svg' alt="some file"  height='100'
width='100' style="color:green;"/>

Embedding an SVG through the <img> element, you need:

  • src attribute
  • height attribute (if your SVG has no inherent aspect ratio)
  • width attribute  (if your SVG has no inherent aspect ratio)

Pros:

  • Easy and quick implementation.
  • Make the SVG image into a hyperlink by nesting <img> & <a> HTML element
  • Caching of SVG file, hence reduced loading time.

Cons:

  • Manipulation of SVG file cannot be done.
  • You can only use inline CSS to style your SVG.
  • Cannot use CSS pseudo-classes to style the SVG.

Example: In this example, we are using img tag for using SVG.

HTML




<!DOCTYPE html>
<html lang="en">
  <body>
    <img
      src=
"https://media.w3wiki.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png"
      alt="gfg-logo"
      height="100"
      width="100"
      style="background-color: green"
    />
  </body>
</html>


Output :

SVG file using HTML <img> element

How to import a SVG file in JavaScript ?

SVG (Scalable Vector Graphics) files in JavaScript are XML-based vector image files commonly used for describing two-dimensional vector graphics. In this article, we are going to see and use different ways of using SVGs.

Below are the methods to import an SVG file in JavaScript:

Table of Content

  • Using HTML img element.
  • Using SVG as an object tag
  • Embedding an SVG with an iframe tag

Similar Reads

Using HTML img element

To include an SVG file in an HTML document using the img element, you can set the src attribute of the img tag to the path of the SVG file....

Using SVG as an object tag

...

Embedding an SVG with an iframe tag

To include an SVG file in an HTML document using the tag, you can specify the SVG file’s path in the data attribute. This method allows for more direct interaction with the SVG content....

Contact Us