Search code examples
ruby-on-railsrubyhpricot

how to remove event attribute from html using Hpricot?


I want to remove a list of dom events attribute from html? how to do this? like:

before = "<div onclick="abc" >abc</div>"
after = clean_it(before) // after => "<div>abc</div>"       


DOM_EVENT_TO_BE_REMOVE = "onclick|ondblclick|onerror|onfocus|onkeydown"  // i want to remove these events

// i want to do it like this
def clean_it(html)
  doc = Hpricot(html)    
  doc.search(DOM_EVENT_TO_BE_REMOVE).remove_attribute(DOM_EVENT_TO_BE_REMOVE) 
  doc.to_s
end

thanks.


Solution

  • Use "remove_attr", E.g:

    doc.search("[@onclick]").remove_attr("onclick")
    

    So for your document do something like:

    DOM_EVENT_TO_BE_REMOVE = ["onclick", "ondblclick", "onerror", "onfocus", "onkeydown"]
    DOM_EVENT_TO_BE_REMOVE.each do |de|
        doc.search("[@#{de}]").remove_attr(de)
    end