Security aside, when you create HTML in JavaScript, you need to make sure that it is valid. Although you can create and sanitize HTML using string manipulation *, manipulating the DOM is much more convenient. However, you must know exactly which part of your line is HTML and which is literal text.
Consider the following example, where we have two hard-coded variables:
var href = "/detail?tag=hr©%5B%5D=1", text = "The HTML <hr> tag";
The following code naively builds an HTML string:
var div = document.createElement("div"); div.innerHTML = '<a href="' + href + '">' + text + '</a>'; console.log(div.innerHTML);
In this case, jQuery is used, but it is still incorrect (it uses .html() for the variable that should have been text):
var div = document.createElement("div"); $("<a></a>").attr("href", href).html(text).appendTo(div); console.log(div.innerHTML);
This is correct because it displays the text as it sees fit:
var div = document.createElement("div"); $("<a></a>").attr("href", href).text(text).appendTo(div); console.log(div.innerHTML);
Conclusion: Using DOM manipulation / jQuery does not guarantee any security, but it is certainly one step in the right direction.
* See this question for an example . Both string and DOM manipulations are discussed.
Salman A Nov 19 '14 at 6:04 2014-11-19 06:04
source share