contentDocument in jQuery
Solution 1
You should be able to access the paths directly like elements, no need for contentDocument or getElementsByTagName, etc:
jQuery(document).ready(function($) {
$(window).load(function () {
$("#alphasvg path").click(function() {
//do stuff
// $(this).attr('d') = the path
})
});
});
Solution 2
Like this:
$(svgDoc).find("whatever").doWhatever();
Demo here and code here. Note that I've used an <iframe>
for demonstration hence the first URL will work, second will give you "permission denied" error if you try to run the fiddle.
Solution 3
If you are embedding SVG into HTML using the object tag (as opposed to inline SVG), this then this is a duplicate of a previous question, the answer to which may be found here: How to access SVG elements with Javascript
user752135
Updated on June 28, 2022Comments
-
user752135 about 2 years
I have the following js script to access elements inside a object (SVG -
<object data="bbbbbb.svg" type="image/svg+xml" id="alphasvg" width="100%" height="100%"></object>
)jQuery(document).ready(function($) { $(window).load(function () { var a = document.getElementById("alphasvg"); var svgDoc = a.contentDocument; var delta = svgDoc.getElementsByTagName("path"); $(delta).click(function() { //do stuff }) }); });
I want to use jQuery to access the elements and tags. I'm completely stuck on the contentDocument part. How can I convert this to jQuery so I can use attr etc?
I want to be able to access and modify attributes in jQuery instead of having to use the traditional js methods which I am unfamiliar with.
How someone can help me?
Thanks a million.
-
Piotr Kula about 13 yearsare you trying to access in-line frame values?
-
-
samccone about 13 yearsthis is correct, the nice thing about svg is the elements are all accessible through the DOM
-
Michael almost 11 yearsI was still getting same origin issues (stackoverflow.com/questions/2753732/…) when I ran without a server, so use a server, even for just client-side js and html as in these examples.