JSFiddle - React, Tailwind, and code Playground

Experiment describing an HTML element with attributes inside the element.

by Laurens Maneschijn

HTML

Experiment describing an element with attributes inside the element.
<hr>
<div
	id="element"
	data-abc-def="camelcaseexample"
	data-empty
	data-emptystring=""
	data-null="null"
	data-true="true"
	data-false="true"
	data-1="1"
	data-json='{x:1,str:"foo"}'
	double="1"
	double="2"
	data-double="1"
	data-double="2"
>
	element
</div>
<!--
Note that double attributes get lost, 
in .outerHTML, element.attributes
-->
sddf

CSS

div {
	display: block;
	border: 1px dashed #888;
	margin: 2px;
	padding: 2px;
	
	white-space: pre;
	font-family: monospace;
	tab-size: 2;
}

JavaScript

init();
function init() {
	draw();
}

function draw() {
	var element = document.getElementById('element');
	// show what the element looks like as html in the result panel:
	
//	element.insertAdjacentElement('afterEnd', element.cloneNode(true));
	// clone nodes to see different results:
	var original = element;
	var new1 = original.cloneNode(true);
	var new2 = original.cloneNode(true);
	// NB: reverse order so end result is: original, new1, new2
	element.insertAdjacentElement('afterEnd', new2);
	element.insertAdjacentElement('afterEnd', new1);
	
	original.setAttribute('title','original');
	new1.setAttribute('title','new1');
	new2.setAttribute('title','new2');

	new1.innerHTML = htmlescape(original.outerHTML);

	new2.innerHTML = elementToHtml(original);

}

function elementToHtml(el) {
	var s = '';
	var nl = '\n';
	var indent = '  ';
	s += '&lt;';
	s += el.tagName;
//	el.attributes.forEach(function(node) {
	Array.from(el.attributes).forEach(function(node) {
		// Interestingly, there is no way to tell if an attribute has a value set.
		// e.g. <div x> and <div x=""> are completely equivalent here.
		s += nl;
		s += indent;
		var name, value, quote, escapedvalue;
		name = node.name; // TODO: .name .nodeName .localName ?
		value = node.value; // TODO: .value .nodeValue .textContent ?
		quote = '"';
		escapedvalue = htmlescape(htmlescape(value));
/*
		var cnt_single_quote = countNeedleInString("'", value);
		var cnt_double_quote = countNeedleInString('"', value);
		quote = cnt_double_quote > cnt_single_quote ? "'" : '"';
		escapedvalue = (quote === "'") ? 
			escape_singlequote(value) :
			escape_doublequote(value)
		;
*/
		s += node.name;
		s += '=';
		s += quote;
		s += escapedvalue;
		s += quote;
	});
	s += nl;
	s += '&gt;';
	return s;
}

function htmlescape(str) {
	// https://stackoverflow.com/questions/6234773/can-i-escape-html-special-chars-in-javascript
	return str
		.replace(/&/g, '&amp;' )
		.replace(/</g, '&lt;' )
		.replace(/>/g, '&gt;' )
		.replace(/"/g,...