Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 9th, 2012  |  syntax: None  |  size: 0.90 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Given a string of html code, how can I go through every tag and remove ones that is not in my whitelist (in JQuery)?
  2. var whitelist = ['a','div','img', 'span'];
  3.        
  4. var canvas = '<div>'+canvas_html+'</div>';
  5.         var blacklist = ['script','object','param','embed','applet','app','iframe',
  6.         'form','input', 'link','meta','title','input','button','textarea'
  7.         'head','body','kbd'];
  8.         blacklist.forEach(function(r){
  9.             $(canvas).find(r).remove();
  10.         });
  11.         canvas_html = $(canvas).get('div').html();
  12.        
  13. var whitelist = ['a','div','img', 'span'];
  14. var output = $('<div>'+canvas_html+'</div>').find('*').each(function() {
  15.   if($.inArray(this.nodeName.toLowerCase(), whitelist)==-1) {
  16.     $(this).remove();
  17.   }
  18. }).html();
  19. // output contains the HTML with everything except those in the whitelist stripped off
  20.        
  21. $(canvas).find(':not(' + whitelist.join(', ') + ')').remove().html();