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

In my Angular app, I want to be able to select an inline SVG tag element <object>using JavaScript or Angular jqLite.

Typically, to complete this operation, you need to 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 body
angular.element(document.body).append(objElement);

console.log(objElement);
console.log(objElement.getSVGDocument());
console.log(objElement.contentDocument);

In my console, it objElementreturns the full <object>element <svg>and its contents (suppose the data attribute contains the full base64 (b64) data string).

    <object id="svgObject" data="b64" type="image/svg+xml">
          #document
             <svg>
             </svg>
    </object>

However getSVGDocument()returns nulland contentDocumentreturns

    #document
       <html>
          <head></head>
          <body></body>
       <html>

Why can't I get an SVG element? How can I get an SVG element correctly? I have already covered a lot of articles and I just can't get the item <svg>. Could this be related to cross-origin policies?

+4
2

SVG, , document.querySelector("svg"), SVG DOM. , :

var obj = document.querySelector("object");
var svg = obj.contentDocument.querySelector("svg");

-, , contentDocument.

+1

, getSVGDocument() . - document.querySelector('object svg')?

0

Source: https://habr.com/ru/post/1613399/


All Articles