Reputation: 12486
Google Chrome v60.0.3112.101, HTML5, jQuery 3.2.1
My object
element is linked with svg
-file. This svg
is displayed without problems on my html page. I try to get svg
element with jQuery but it found nothing for my both attemptions:
$('object').length; // 1
$('svg').length; // 0
$('object > svg').length; // 0
this is my html chunk:
<object type='text/svg+xml' data='svg/logo.svg'></object>
How can I get my svg
with jQuery?
P.S. I use this method (an external svg
-file) because my svg
will be used on many web-pages. Also I use object
instead of img
because that svg
uses an external css
-file.
Upvotes: 3
Views: 5843
Reputation: 1
You can access the object, if you add an id
<object id="svg" type='text/svg+xml' data='svg/logo.svg'></object>
then you can query for the id like this
$('#svg')
Upvotes: 0
Reputation: 101820
You need to use the contentDocument
property of the <object>
element. That'll give you the document object that is the parent of the <svg>
element. Then you can use the documentElement
property of the document object to get the root element of the document, which will be the <svg>
element.
var svg = $("object")[0].contentDocument.documentElement;
To visualise that:
#document
<html> (HTMLDocument)
<object> (HTMLObjectElement) $("object")[0]
#document (HTMLDocument) .contentDocument
<svg> (SVGSVGElement) .documentElement
But remember that the SVG won't be accessible until the page has finished loading. So you need to wait for the Window onload
event.
$(window).on("load", function() {
var svg = $("object")[0].contentDocument.documentElement;
console.log("svg = ",svg);
});
Upvotes: 3