arrow_back
Back

Working with JS

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

We should use namespaces.

var ns = {
    svg: "http://www.w3.org/2000/svg",
    xlink: "http://www.w3.org/1999/xlink"
};
var svg = document.createElementNS(ns.svg, "svg");
var use = document.createElementNS(ns.svg, "use");
use.setAttributeNS(ns.xlink, "href", "#icon");
svg.appendChild(use);
document.body.appendChild(svg);

More simple:

var div = document.createElement("div");
div.innerHTML = '<svg><use xlink:href="#icon" /></svg>'
document.body.appendChild(div.firstChild);

Scripts in standalone SVG

SVG also has its own <script> element. To add JavaScript to a standalone SVG file, you can include a <script> element anywhere between the opening and closing <svg> tags. The SVG <script> element is very similar to its HTML counterpart, but they aren’t identical.

If you include a <script> element as a child of an <svg> element that is inline in HTML, the parser will create an SVGScriptElement, not an HTMLScriptElement.

To include an external JavaScript file with an SVG <script> element, use an xlink:href attribute (not src like in HTML) to give the file location.

<svg xmlns="http://www.w3.org/2000/svg" xml:lang="en" xmlns:xlink="http://www.w3.org/1999/xlink" >
    <title>My Standalone D3 Data Visualization</title>
    <script xlink:href="/assets/d3.min.js" />
    <script><![CDATA[
        if (1 < 0) {
        console.log("Uh oh, math is broken.",
        "But my XML markup isn't.");
        }
        /* more & more JS code */
    ]]></script>
</svg>

The <![CDATA[ ... ]]> structure can be used anywhere in an XML file to indicate that the enclosed text should be treated as plain text, not markup. It’s usually required for JavaScript, and can also be used for CSS code that might have special characters in comments.

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Basic terms

arrow_forward