Skip to content Skip to sidebar Skip to footer

Append Html To Jquery Element Without Running Scripts Inside The Html

I have written some code that takes a string of html and cleans away any ugly HTML from it using jQuery (see an early prototype in this SO question). It works pretty well, but I st

Solution 1:

How about removing the scripts first?

var wrapper = $('<div/>').append($(html).not('script'));

  • Create the div container
  • Use plain JS to put html into div
  • Remove all script elements in the div

Assuming script elements in the html are not nested in other elements:

var wrapper = document.createElement('div');
wrapper.innerHTML = html;
$(wrapper).children().remove('script');

var wrapper = document.createElement('div');
wrapper.innerHTML = html;
$(wrapper).find('script').remove();

This works for the case where html is just text and where html has text outside any elements.

Solution 2:

You should remove the script elements:

var wrapper = $('<div/>').append($(html).remove("script"));

Second attempt:

node-validator can be used in the browser: https://github.com/chriso/node-validator

var str = sanitize(large_input_str).xss();

Alternatively, PHPJS has a strip_tags function (regex/evil based): http://phpjs.org/functions/strip_tags:535

Solution 3:

The scripts in the html kept executing for me with all the simple methods mentioned here, then I remembered jquery has a tool for this (since 1.8), jQuery.parseHTML. There's still a catch, according to the documentation events inside attributes(i.e. <img onerror>) will still run.

This is what I'm using:

var $dom = $($.parseHTML(d));

$dom will be a jquery object with the elements found

Post a Comment for "Append Html To Jquery Element Without Running Scripts Inside The Html"