In my Angular appliation, I want to be able to select the embedded SVG element of an <object>
tag using JavaScript or Angular jqLite.
Normally, to do this operation, one must write something similar to:
// Create <object> element of the SVG
var objElement = document.createElement('object');
objElement.setAttribute('type',"image/svg+xml");
// Assume $rootScope.b64 contains the base64 data of the SVG
objElement.setAttribute('data', $rootScope.b64);
// Append the <object> inside the DOM's body
angular.element(document.body).append(objElement);
console.log(objElement);
console.log(objElement.getSVGDocument());
console.log(objElement.contentDocument);
In my console, objElement
returns the complete <object>
with the <svg>
element and its contents (assume that data attribute contains the full base64 data string (b64)).
<object id="svgObject" data="b64" type="image/svg+xml">
#document
<svg>
</svg>
</object>
However, getSVGDocument()
returns null
and contentDocument
returns
#document
<html>
<head></head>
<body></body>
<html>
Why can't I retrieve the SVG element? How can I get the SVG element correctly? I've already looked into many articles and I just can't get the <svg>
element. Could this have something to do with cross-origin policy?
To click the element with svg, we should identify the element then utilize the Actions class. We shall first move to that element with the moveToElement method and then apply the click method on it. Finally, to actually perform the action, we have to use the build and execute methods.
I was also unable to select the SVG using things like document.querySelector("svg")
even though the SVG was clearly loaded in the DOM. Turned out I needed to do this:
var obj = document.querySelector("object");
var svg = obj.contentDocument.querySelector("svg");
Apparently there's a boundary between the main document and this sub-document, and you have to bridge the divide using contentDocument
.
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