outerHTML of an SVG element

前端 未结 5 1992
天命终不由人
天命终不由人 2020-12-09 03:46

Why can not we get outerHTML of an svg element with element.outerHTML property?

Is this way is the best http://jsfiddle.net/33g8g/ for getting svg sourc

5条回答
  •  心在旅途
    2020-12-09 04:09

    It's not accessible via outerHTML because SVG is not HTML -- it's a separate XML specification.

    That's why, for example, your svg node in that example has its own namespace defined (xmlns="http://www.w3.org/2000/svg).

    Your example may be the most expedient for a one-off query, but it's actually possible to dig in using native attributes. It just takes a bit more work.

    Let's use the linked sample node:

     
        An SVG element.
     
    

    If you want to extract the namespace and version, use the attributes property.

    var svgElement = $('svg')[0]; // using your example
    console.log(svgElement.attributes.xmlns); // outputs "http://www.w3.org/2000/svg"
    console.log(svgElement.attributes.version); // outputs "1.1"
    

    If you want to extract the actual contents, iterate over the children. Similar to the above, a non-text node's attributes collection will contain the x/y values (etc).

    Without using jQuery, using your example again:

    for (var i = 0; i < svgElement.childNodes.length; i++) {
        var child = svgElement.childNodes[i];
        if (child.nodeType == 1) {
            console.log(child.attributes[0].name); // "x"
            console.log(child.attributes[0].value); // "0"
            console.log(child.attributes[1].name); // "y"
            console.log(child.attributes[1].value); // "15"
        }
    }
    

    Here's an updated Fiddle, a bit more elegantly demonstrating the possibilities: http://jsfiddle.net/33g8g/8/

提交回复
热议问题