Jonathan
Jonathan

Reputation: 3024

How do I use innerHTML with createTextNode?

I'm trying to create a chrome extension and im doing this by parsing an RSS feed with XMLHttpRequest and then storing the tokens parsed, such as title & description, into an array.

After parsing the feed and storing the tokens into an array, I then loop through the array and display them onto the chrome extension popup using DOM. It works but the problem is that each description has HTML tags and shows up something like this:

<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 [...]

The HTML tags come from the feed and I have no problem with them all I want to do is get them to be actually interpreted as HTML rather than as text. I believe this is because im using createTextNode? I should be using innerHTML? I'm not sure how to use innerHTML in the following example?

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

I can post more of my code up if that will help?

Upvotes: 3

Views: 8075

Answers (1)

RobG
RobG

Reputation: 147343

Try:

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

createTextNode creates a text node, the string passed to it is treated as plain text and assigned to the node's data property. The string assigned to the innerHTML property is treated as markup and is parsed by the browser's HTML parser (or XML parser in very recent browsers in the case of an XML document) and turned into DOM elements.

Upvotes: 9

Related Questions