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(draggableIcon);
				newOptionListRow.appendChild(document.createTextNode(' '));

				optionList.appendChild(newOptionListRow);

				newKeyInput.onfocus = doExpandList

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

				newKeyInput.onfocus = doExpandList
				newInput.value = '';

				newInput.id = optionItemPrefix+'_options['+newId+']';
				newOptionListRow.appendChild(document.createTextNode(' '));
				newOptionListRow.appendChild(newInput);
1 Like

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.

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: