I need to edit (using javascript) an SVG document embedded in an html page.
When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded.
To access the SVG dom, I use this code:
var svg = document.getElementById("chart").getSVGDocument();
where "chart" is the id of the embed element.
If I try to access the SVG when the html document is ready, in this way:
jQuery(document).ready( function() { var svg = document.getElementById("chart").getSVGDocument(); ...
svg is always null. I just need to know when it is not null, so I can start manipulate it. Do you know if there is a way to do it?
The quick way: img elementTo embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.
Embedded content is content that imports into the document from another resource. SVG <image> and <foreignObject> elements are used for SVG embedded content support.
The SVG format allows for the nesting of SVG graphics. It is possible for an “<svg>” elements, to be placed within another “<svg>” element.
On your embedding element (e.g 'embed', 'object', 'iframe') in the main document add an onload
attribute which calls your function, or add the event listener in script, e.g embeddingElm.addEventListener('load', callbackFunction, false)
. Another option might be to listen for DOMContentLoaded
, depends on what you want it for.
You can also add a load listener on the main document. jQuery(document).ready
doesn't mean that all resources are loaded, just that the document itself has a DOM that is ready for action. However note that if you listen for load on the entire document your callback function won't be called until all resources in that document are loaded, css, javascript etc.
If you use inline svg, then jQuery(document).ready
will work just fine however.
On a further note you might want to consider using embeddingElm.contentDocument
(if available) instead of embeddingElm.getSVGDocument()
.
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