Suggestions for a cleaner way to write HTML in JavaScript

Hi everyone,

I’m wondering if anyone knows of a nice compact little library, or perhaps just a design pattern, that would help me write clean HTML within JavaScript. What I mean by “clean” is just a nice way to represent the creation of HTML via templating…

It’s a tricky situation, because the way things are at work means that a lot of our HTML is created using the JS API: document.createElement() and el.setAttribute(). This is fine for small amounts of HTML, but when it starts to get beyond 20+ lines, things start to become sooooo hard to follow…

Is there something like a minimal implementation of JSX out there? Just something to help with clean templating. Oh, and ES6 isn’t an option :frowning:

Thanks in advance! :slight_smile:

For a killer exmaple, here’s the kinda stuff I’m up against on a daily basis:

				var newOptionListRow = document.createElement('div');
				newOptionListRow.setAttribute('class', 'sq-option-list-row mb-10');
				var draggableIcon = document.createElement('span');
				draggableIcon.setAttribute('class', 'sq-draggable-item js_sq-draggable-item ui-sortable-handle')
				newOptionListRow.appendChild(document.createTextNode(' '));


				newKeyInput.onfocus = doExpandList

				newKeyInput.value = ''; = optionItemPrefix+'_options_keys['+newId+']';
				newOptionListRow.appendChild(document.createTextNode(' '));

				newKeyInput.onfocus = doExpandList
				newInput.value = ''; = optionItemPrefix+'_options['+newId+']';
				newOptionListRow.appendChild(document.createTextNode(' '));
1 Like

If ES6 is not possible, what about using Babel to transpile to ES5 while still utilizing ES6 features like template literals?

Yeah I think I really need to push ES6 onto the tech stack! But are there issues with Template Literals and XSS?

The reason we use the standard JS API is because using createElement() escapes values that cause XSS issues.

Not 100% sure, but it seems like they would be. I found the following SO thread, where a question regarding using template literals to eval is compared. Maybe you can gain some insight from it.

Also, this is a good read also:

1 Like

After reading through both of the links I listed above and doing a little more research, you still have to sanitize any data you put into the template literals, the same as you would if you were building a string via concatenation of variables containing user content.

1 Like

Yeah sanitizing shouldn’t be too big of an issue, but testing malicious strings might be difficult as I don’t know exactly all the cases I should test for. It’s a bit of guesswork. I really wish I could just use React and JSX :frowning:

Thanks for all the info, I appreciate the help :slight_smile: