jQuery Executes Script Tags in SubNodes

I recently wanted to clean a string of all HTML in order to use it as a title. Our users occasionally paste things into the title they shouldn’t, and while they have that right, it’s easier to prevent breakage and just use text instead of allowing them to break things. Since we use jQuery, I figured the following code might work:


this does strip out all html from the string as expected, but with one unintended consequence—if the titleString contains the html for a script tag, that tag will be run.

$('<div>').html('<script>alert("Bad Idea!")</script>').text();
// Alerts 'Bad Idea!' then returns only the text.

The solution is to remove the initial div declaration.

$('<script>alert("Bad Idea!")</script>').text();
// just returns the text.

jQuery only executes script tags in children of tags, not the initial creation.

Dynamically Add Collapsible Elements in Jquery Mobile

I spent a long time trying to get this to work and finally success.
This code produces a div with content and then reminds the JQuery Mobile framework to actually wire it up with classes, functionality, etc.

$('<div data-role="collapsible"><h3>Title</h3><p>Content</p></div>').appendTo('[data-role="content"]');