Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an SVG element inside an <object> tag with JavaScript?

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?

like image 663
Dramos Avatar asked Oct 27 '15 19:10

Dramos


People also ask

How do I click an SVG element?

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.


1 Answers

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.

like image 51
Josh Hansen Avatar answered Oct 30 '22 16:10

Josh Hansen