2012-09-25 149 views

回答

4

它不能通過outerHTML訪問,因爲SVG不是HTML--它是一個單獨的XML specification

這就是爲什麼,例如,您的示例中的svg節點有其自己的名稱空間定義(xmlns="http://www.w3.org/2000/svg)。

您的示例可能是一次性查詢的最有利方法,但實際上可以使用本機屬性進行挖掘。它只需要更多的工作。

讓我們用鏈接的樣本節點:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1"> 
    <text x="0" y="15" fill="black">An SVG element.</text> 
</svg> 

如果要提取的命名空間和版本,使用attributes屬性。

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" 

如果要提取實際內容,請遍歷子項。與上面類似,非文本節點的attributes集合將包含x/y值(等)。

沒有使用jQuery,再次使用例如:

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" 
    } 
} 

這裏有一個更新的小提琴,有點更優雅展示了可能性: http://jsfiddle.net/33g8g/8/

19

SVGElements沒有的outerHTML屬性。

你可以這樣定義的純JavaScript

Object.defineProperty(SVGElement.prototype, 'outerHTML', { 
    get: function() { 
     var $node, $temp; 
     $temp = document.createElement('div'); 
     $node = this.cloneNode(true); 
     $temp.appendChild($node); 
     return $temp.innerHTML; 
    }, 
    enumerable: false, 
    configurable: true 
}); 

或者一個行jQuery的解決辦法是

$('<div>').append($(svgElement).clone()).html(); 

參考: https://gist.github.com/jarek-foksa/2648095

+0

感謝分享這 - 是具有一個時間赫克得到outerHTML在Safari中工作! – aendrew

+0

我會在polyfill –

6

2013更新:innerHTMLouterHTML將被svg eleme支持nts也是,每DOM Parsing specification

此修補程序已在Blink/Chrome中着陸,很快就會發布,請參閱http://code.google.com/p/chromium/issues/detail?id=311080

+0

的周圍添加if(!('SVGlement.prototype的outerHTML')){/ ** * /}哇,這很好。 – ivkremer

+3

我可以確認這適用於最新版本的Chrome,Safari和Firefox。唉,它不適用於Internet Explorer 11。 – Husky

1

使用jQuery,您可以輕鬆地創建周圍的任何元素的臨時HTML包裝,不支持outerHTML:

function wrappedHtml(elt){ 
    var wrapped = elt.wrap("<wrap></wrap>").parent().html(); 
    elt.unwrap(); 
    return wrapped; 
} 
1

這是一個簡單的解決方案,它在FF,Chrome瀏覽器,IE瀏覽器的偉大工程。榮譽去Philipp Wrann

outerHtml is not working in IE

new XMLSerializer().serializeToString(document.querySelector('#b'))