2012-09-25 4 views

답변

4

SVG가 HTML이 아니기 때문에 outerHTML을 통해 액세스 할 수 없습니다. 별도의 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에 속성이 없습니다.

당신은 순수 자바 스크립트

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 주위에'if ('(SVGElement.prototype의 outerHtml')) {/ ** * /}'를 추가 할 것입니다. –

6

2013 업데이트 :innerHTMLouterHTML은 svg eleme에서 지원됩니다. nts도 DOM Parsing specification 당.

이 패치는 Blink/Chrome에 제공되었으며 곧 제공 될 예정입니다. http://code.google.com/p/chromium/issues/detail?id=311080을 참조하십시오. jQuery를 사용

+0

와우, 멋지 네. – ivkremer

+3

이 버전은 Chrome, Safari 및 Firefox의 최신 버전에서 완벽하게 작동합니다. 아아, Internet Explorer 11에서는 작동하지 않습니다. – Husky

1

, 당신은 쉽게 outerHTML에를 지원하지 않는 요소 주위 임시 HTML 래퍼 만들 수 있습니다

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

이 쉬운 솔루션을 그리고 FF, 크롬, IE에서 잘 작동합니다. 명예는 Philipp Wrann입니다. 그 공유를위한

outerHtml is not working in IE

new XMLSerializer().serializeToString(document.querySelector('#b')) 
관련 문제