Skip to content

Instantly share code, notes, and snippets.

@robertuniqid
Created September 27, 2020 21:23
Show Gist options
  • Save robertuniqid/5c6efb198ac3185903fa0bf0ef339390 to your computer and use it in GitHub Desktop.
Save robertuniqid/5c6efb198ac3185903fa0bf0ef339390 to your computer and use it in GitHub Desktop.
Element to Zencoding
<html>
<head>
<title>Element to Zen</title>
<meta charset="UTF-8">
<script>
function element_to_zen( element ) {
let response_map = [],
_default_mapping = {
priority : 5,
parse : function( nodeName, nodeValue ) {
return '[' + nodeName + '=' + nodeValue + ']';
}
},
_special_mapping = {
id : {
priority : 1,
parse : function( nodeName, nodeValue ) {
return '#' + nodeValue;
}
},
class : {
priority : 2,
parse : function( nodeName, nodeValue ) {
let _temp = nodeValue.split( ' ' );
return '.' + _temp.join( '.' );
}
},
className : {
priority : 3,
parse : function( nodeName, nodeValue ) {
return '.' + nodeValue;
}
}
};
if( typeof element.attributes === 'undefined' )
return '';
Object.keys( element.attributes ).map( function( objectKey, index ) {
let _current_attribute = element.attributes[ objectKey ],
_current_mapping = ( typeof _special_mapping[ _current_attribute.nodeName ] !== 'undefined' ? _special_mapping[ _current_attribute.nodeName ] : _default_mapping );
if( typeof response_map[ _current_mapping.priority ] === 'undefined' )
response_map[ _current_mapping.priority ] = [];
response_map[ _current_mapping.priority ].push( _current_mapping.parse( _current_attribute.nodeName, _current_attribute.nodeValue ) );
});
let response = '';
response_map.forEach( function( current_items ) {
response += current_items.join("");
});
return response;
}
</script>
</head>
<body>
<div id="not-pushing" class="my-class-name and-yes this-will-do" data-custom-attribute="my-custom-attr" data-custom-attr-2="hello-world"></div>
<script>
(function() {
alert( element_to_zen( document.getElementById("not-pushing") ) );
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment