Use TextNodes to protect against XSS

Also encapsulated the logic. This results in a larger diff. I can try again without encapsulating the logic if this will help.