从XML字符串创建DOM元素,如何使用.getElementsByName()?

时间:2016-04-24 03:24:38

标签: javascript xml dom

所以我试图将从XML字符串创建的DOM元素插入到我的文档中。但首先,我试图修改该字符串中某些元素的innerText。我试图使用以下内容......

refElem = document.createElement('div');
refElem.innerHTML = xmlString;
...
newChild = document.createElement('div');
newChild.innerHTML = refElem.innerHTML;
newChild.getElementsByName('title') ...

但我收到以下错误:

main.js:140 Uncaught TypeError: newChild.getElementsByName is not a function

任何人都知道如何将xml字符串解析为DOM元素并在将其插入页面之前操作该元素?

没有jquery的答案请!只有香草JS!

1 个答案:

答案 0 :(得分:0)

getElementsByNamegetElementByID是DOM文档对象的函数,而不是DOM元素对象。要搜索DOM元素对象,请使用querySelector或`querySelectorAll。

例如:

newChild.querySelectorAll('#title');