2015-06-18 165 views
5

我試圖在我的特定節點(<name>)之前插入註釋節點XML。下面是它的方法:未能在'Node'上執行'insertBefore':之前要插入新節點的節點不是此節點的子節點

function test(xmlResponse) 
{ 
    var parser = new DOMParser(), xmlDoc = parser.parseFromString(xmlResponse,"text/xml"); 

    var comentDocument = document.createComment("My personal comments"); 

    console.log(xmlDoc.querySelectorAll("street name")[0]) 
    xmlDoc.insertBefore(comentDocument , xmlDoc.querySelectorAll("street name")[0]); 

    return xmlDoc 
} 

,當我打電話:

test("<address><street><name>Street name</name></street></address>") 

我得到:

<name>Street name</name> 
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. 
    at Error (native) 
    at generateTheComment (<anonymous>:12:9) 
    at <anonymous>:2:1 
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140) 
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34) 
    at Object.InjectedScript.evaluate (<anonymous>:694:21) 

正如你可以看到<name>Street name</name>是越來越正確打印;因爲我想將comentDocument附加到其父母<street>

不知道我在這裏犯了什麼錯誤。

我期待的代碼即可返回:

<address> 
    <street> 
    <!-- My personal comments --> 
    <name>Street name 
    </name> 
    </street> 
</address> 
+1

嗯,好像你不想插在'xmlDoc'是評論,但在''節點。 – Bergi

+0

相關:http://stackoverflow.com/questions/3352871/using-javascript-insertbefore-to-insert-before-a-textnode –

回答

3
xmlDoc.insertBefore(comentDocument , xmlDoc.querySelectorAll("street name")[0]); 

這將嘗試從文檔中直接插入。你需要讓你想插入註釋元素的直接父前:

var name = xmlDoc.querySelector("street name"); 
name.parentNode.insertBefore(comentDocument, name);