Guest User

Untitled

a guest
May 9th, 2012
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  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();
Advertisement
Add Comment
Please, Sign In to add comment