How to use SVG as an object tag In Javascript
To include an SVG file in an HTML document using the <object>
tag, you can specify the SVG file’s path in the data
attribute. This method allows for more direct interaction with the SVG content.
Syntax:
<object type="image/svg+xml" data="logo.svg" class="logo">
Logo
</object>
Embedding a SVG via a <object> element requires:
- type attribute
- data attribute
- class attribute ( if using external/internal CSS )
Pros:
- You can use external/internal CSS to style SVG.
- Easy and quick implementation.
- Will work great with caching.
Cons:
- To use an external stylesheet, you need to use an <style> element inside the SVG file.
- Not so familiar with syntax and implementation.
Example: In this example, we are using object tag for using SVG.
HTML
<!DOCTYPE html> < html lang = "en" > < body > < object type = "image/svg+xml" data = "https://media.w3wiki.org/wp-content/cdn-uploads/20210205161739/Screenshot-2021-02-05-161721.png" class = "logo" > GFG Logo </ object > </ body > </ html > |
Output:
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
Contact Us