Home >Web Front-end >JS Tutorial >How to Access SVG Elements from Illustrator-Generated Files with JavaScript?
Accessing SVG Elements with JavaScript from Illustrator-Generated SVG Files
As discussed, accessing SVG elements with JavaScript from SVG files created in Adobe Illustrator is indeed possible without utilizing third-party libraries like Raphaël or jQuery SVG.
To achieve this:
1. Load the SVG File Asynchronously:
Incorporate an HTML5
<object data="alpha.svg" type="image/svg+xml">
2. Add Load Event Listener:
Attach a load event listener to the
<script> var a = document.getElementById("alphasvg"); a.addEventListener("load",function(){ // code here executes after SVG loads }, false); </script>
3. Retrieve Inner DOM and Access Elements:
Within the load event callback, manipulate the SVG document's inner DOM by retrieving it:
var svgDoc = a.contentDocument;
Using this reference to svgDoc, you can access specific elements by their IDs using the getElementById method:
var delta = svgDoc.getElementById("delta");
4. Add Event Handlers:
Once you have access to the elements, you can attach event handlers for behaviors. For instance, to add a click handler to the 'delta' element:
delta.addEventListener("mousedown",function(){ alert('hello world!') }, false);
Limitations:
This technique is subject to the same-origin policy. Therefore, the SVG file must be hosted on the same domain as the HTML file to ensure access to the inner DOM.
The above is the detailed content of How to Access SVG Elements from Illustrator-Generated Files with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!