如何将innerHTML与createTextNode一起使用?

时间:2011-11-07 00:40:42

标签: javascript html dom

我正在尝试创建一个chrome扩展,并通过使用XMLHttpRequest解析RSS提要,然后存储已解析的标记,例如title& description,放入数组。

解析feed并将令牌存储到数组中后,我遍历数组并使用DOM将它们显示在chrome扩展弹出窗口中。它有效,但问题是每个description都有HTML标记,并显示如下内容:

<p><img src="http://www.documentarywire.com/cover/college-inc.jpg" width="90" height="100" style="float:left; padding: 0 10px 20px 0"/></p>Even in lean times, the $400 billion business of higher education is booming. Nowhere is this more true than in one of the fastest-growing &#8212; and most controversial &#8212; sectors of the industry: for-profit colleges and universities that cater to non-traditional students, often confer degrees over the Internet, and, along the way, successfully capture billions [...]

HTML标记来自feed,我对它们没有任何问题我想要做的就是将它们实际解释为HTML而不是文本。我相信这是因为我使用createTextNode?我应该使用innerHTML?我不确定如何在以下示例中使用innerHTML?

   var descriptionNode = document.createElement("div");
   descriptionNode.setAttribute("class", "description");
   descriptionNode.appendChild(document.createTextNode(item["description"]));
   detail.appendChild(descriptionNode);

如果有帮助,我可以发布更多代码吗?

1 个答案:

答案 0 :(得分:6)

尝试:

var descriptionNode = document.createElement("div");
descriptionNode.className = "description";
descriptionNode.innerHTML = item["description"];
detail.appendChild(descriptionNode);

createTextNode 创建一个文本节点,传递给它的字符串被视为纯文本并分配给节点的数据属性。分配给 innerHTML 属性的字符串被视为标记,并由浏览器的HTML解析器(或XML文档中最近的浏览器中的XML解析器)解析并转换为DOM元素。