4

I'm looking for a HTML to real JavaScript (online) converter. With 'real' I mean creating all elements and all attributes with JS. There are multiple tools online that convert HTML to JavaScript but use other solutions, e.g.

  1. Not document.write()
  2. Not element.innerHTML
  3. Not jQuery.HTML()

Example:

<div id="testid">
    <span class="text" data-attribute="value">Text</span>
</div>

To

var elmDiv = document.createElement('div');
elmDiv.setAttribute('id', 'testid');
var elmSpan = document.createElement('span');
elmSpan.classList.add('text');
elmSpan.dataset['attribute'] = 'value';
elmSpan.appendChild(document.createTextNode('Text'));
elmDiv.appendChild(elmSpan);
  • Does it have to be based on node.js? If so, you would ideally state this in the question. If not, you should remove the tag (as tags should only be used for requirements). -- And does it have to be "online", i.e., a Web app, or is a local solution okay, too? If yes, for which operating system? – unor Mar 28 '15 at 20:14
  • 1
    If it's a library I could use it in Node.js, but that's not a requirement. A web-based online converter is sufficient. Removed the tag. – jerone Mar 28 '15 at 21:52
  • I assume that JavaScript can just hand the browser an HMTL text string and say "process this into a DOM". (Do I have that right?) If so, what would be the value of making JS that creates all the DOM elements one by one? – Ira Baxter Aug 15 '16 at 1:13
3

I could not find anything either so i wrote it myself and put it up on https://github.com/n-a-m-e/convert-html-to-javascript I'm pretty sure I thought of everything but if you can think of anything I missed please don't hesitate to improve upon my work.

<!DOCTYPE html>
<html>
<head>
    <title>Convert HTML to Javascript</title>
    <script type="text/javascript">
        function convertHTMLtoJavascript(input,keepWhitespace){
            //This works in all modern browser. If your using IE (which you shouldn't be) switch to a browser that supports html5 templates.
            function loopThroughChildNodes(parent,parentNestLevel){
                var elementCounter = 0;
                var textNodeCounter = 0;
                var parentElement = "element" + parentNestLevel;
                var Nodes = parent.childNodes;
                for(var i = 0, currentNode; (currentNode = Nodes[i]) !== undefined; i++){
                    if (currentNode.nodeType == 1){
                        elementCounter++;
                        var currentNestLevel = parentNestLevel + '_' + elementCounter;
                        var currentElement = "element" + currentNestLevel;
                        createElements += '\n\t' + 'var ' + currentElement + ' = document.createElement("' + currentNode.tagName.toLowerCase() + '");';
                        Array.prototype.slice.call(currentNode.attributes).forEach(function(attribute) {
                            setAttributes += '\n\t' + currentElement + '.setAttribute("' + attribute.name + '","' + attribute.value + '");';
                        });
                        appendChildren += '\n\t' + parentElement +'.appendChild(' + currentElement + ');';
                        loopThroughChildNodes(currentNode,currentNestLevel);
                    }else{
                        if(keepWhitespace===true){
                            var text = currentNode.textContent;
                        }else{
                            var text = currentNode.textContent.trim();
                        }
                        if (text!=""){
                            textNodeCounter++;
                            var currentNestLevel = parentNestLevel + '_' + textNodeCounter;
                            var currentTextNode = "textNode" + currentNestLevel;
                            createTextNodes += '\n\t' + 'var ' + currentTextNode + ' = document.createTextNode("' + text.replace(/"/g,'\\x22') + '");';
                            appendChildren += '\n\t' + parentElement +'.appendChild(' + currentTextNode + ');';
                        }
                    }
                }
            }
            var temp = document.createElement('template');
            var createElements = "";
            var createTextNodes = "";
            var setAttributes = "";
            var appendChildren = "";
            temp.innerHTML = input;
            var documentFragment = temp.content;
            loopThroughChildNodes(documentFragment,"");
            if (createElements!="") createElements = '\n\t' + '//Create Elements' + createElements;
            if (createTextNodes!="") createTextNodes = '\n\t' + '//Create Text Nodes' + createTextNodes;
            if (setAttributes!="") setAttributes = '\n\t' + '//Set Attributes' + setAttributes;
            if (appendChildren!="") appendChildren = '\n\t' + '//Append Children' + appendChildren;
            var output = '//to append the html to an element simply write:';
            output += '\n' + '//appendHTMLto(document.getElementById("parent"));';
            output += '\n\n' + 'function appendHTMLto(element){';
            output += createElements;
            output += createTextNodes;
            output += setAttributes;
            output += appendChildren;
            output += '\n' + '}';
            return output;
        }
        function convert(){
            var input = document.getElementById("input").value;
            var keepWhitespace = document.getElementById("whitespace").checked;
            document.getElementById("output").value = convertHTMLtoJavascript(input,keepWhitespace);
        }
    </script>
    <style type="text/css">
        .form{
            font-family: "HelveticaNeue", "Helvetica", "Arial", sans-serif;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            width:90%;
            padding:30px;
            margin:40px auto;
            background: #FFF;
            border-radius: 10px;
            -webkit-border-radius:10px;
            -moz-border-radius: 10px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.13);
            -moz-box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.13);
            -webkit-box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.13);
        }
        .inner-wrap{
            padding: 30px;
            background: #F8F8F8;
            border-radius: 6px;
            margin-bottom: 15px;
        }
        h1{
            background: #2A88AD;
            padding: 20px 30px 15px 30px;
            margin: -30px -30px 30px -30px;
            border-radius: 10px 10px 0 0;
            -webkit-border-radius: 10px 10px 0 0;
            -moz-border-radius: 10px 10px 0 0;
            color: #fff;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.12);
            font-size: 30px;
            -moz-box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.17);
            -webkit-box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.17);
            box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.17);
            border: 1px solid #257C9E;
        }
        h1 > span{
            display: block;
            margin-top: 2px;
            font-size: 13px;
        }
        label{
            display: block;
            font-size: 13px;
            color: #888;
            margin-bottom: 15px;
        }
        textarea{
            resize: vertical;
            -moz-border-bottom-colors: none;
            -moz-border-left-colors: none;
            -moz-border-right-colors: none;
            -moz-border-top-colors: none;
            background: none repeat scroll 0 0 rgba(0, 0, 0, 0.07);
            border-color: -moz-use-text-color #FFFFFF #FFFFFF -moz-use-text-color;
            border-image: none;
            border-radius: 6px 6px 6px 6px;
            border-style: none solid solid none;
            border-width: medium 1px 1px medium;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12) inset;
            color: #555555;
            font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
            font-size: 1em;
            line-height: 1.4em;
            padding: 5px 8px;
            transition: background-color 0.2s ease 0s;
            display: block;
            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            width: 100%;
            height: 200px;
            padding: 8px;
            border-radius: 6px;
            -webkit-border-radius:6px;
            -moz-border-radius:6px;
            border: 2px solid #fff;
            box-shadow: inset 0px 1px 1px rgba(0, 0, 0, 0.33);
            -moz-box-shadow: inset 0px 1px 1px rgba(0, 0, 0, 0.33);
            -webkit-box-shadow: inset 0px 1px 1px rgba(0, 0, 0, 0.33);
            font-family: "Courier New", "Courier", "Lucida Sans Typewriter", "Lucida Typewriter",monospace;
        }
        textarea:focus {
            background: none repeat scroll 0 0 #FFFFFF;
            outline-width: 0;
        }
        .section{
            font-size: 20px;
            color: #2A88AD;
            margin-bottom: 5px;
        }
        .section span {
            background: #2A88AD;
            padding: 5px 10px 5px 10px;
            position: absolute;
            border-radius: 50%;
            -webkit-border-radius: 50%;
            -moz-border-radius: 50%;
            border: 4px solid #fff;
            font-size: 14px;
            margin-left: -45px;
            color: #fff;
            margin-top: -3px;
        }
        button{
            background: #2A88AD;
            margin: 10px;
            padding: 8px 20px 8px 20px;
            border-radius: 5px;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            color: #fff;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.12);
            -moz-box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.17);
            -webkit-box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.17);
            box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.17);
            border: 1px solid #257C9E;
            font-size: 15px;
        }
        button:hover{
            background: #2A6881;
            -moz-box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.28);
            -webkit-box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.28);
            box-shadow: inset 0px 2px 2px 0px rgba(255, 255, 255, 0.28);
        }
        .option{
            width: 250px;
            font-size: 12px;
            color: #4D4D4D;
            margin-top: 10px;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="form">
        <h1>Convert your HTML to Javascript Now!<span>This works in all modern browser. If your using IE (which you shouldn't be) switch to a browser that supports html5 templates.</span></h1>
        <div class="section"><span>1</span>Enter the HTML you wish to convert</div>
        <div class="inner-wrap">
            <label>HTML Input <textarea id="input" name="input"></textarea></label>
        </div>
        <button onclick="convert()">Convert</button>
        <span class="option">
            <input type="checkbox" id="whitespace">Don't get rid of the whitespace in my HTML
        </span>
        <div class="section"><span>2</span>Copy the Javascript</div>
        <div class="inner-wrap">
            <label>Javascript Output <textarea id="output" name="output"></textarea></label>
        </div>
    </div>
</body>
</html>
  • That's awesome! Exactly what I was looking for. Any plans to put this live, make it a library or NodeJS module? – jerone Apr 27 '15 at 13:11
1

I don't think this is completely what your after, but it may be useful anyway.

The first few results of Google are:

AndrewDavidson.com

Converts your example to

document.write( '<div id=\"testid\">\n' );
document.write( '    <span class=\"text\" data-attribute=\"value\">Text</span>\n' );
document.write( '</div>' );

Accessify.com

Generates the same as above. But also can do other things, such as output as document.write statements wrapped in a function or Build up a string variable that you can use later

Then there's grunt-html-to-js - a script that runs on grunt, but as I do not have grunt running on my server, I cannot test it, only go by the description. Which is this:

This plugin converts a group of html files to JavaScript and assembles them into an vanilla javascript. Note that this plugin does not compile the templates. It simply caches the template source code.

  • Thank you for your answer. There are a lot of similar tools like the one mentioned by you, but that's exactly what I didn't want. See point 1 from the question, document.write(). – jerone Apr 17 '15 at 17:46
  • Ah sorry, I missed that. I don't know of any that do that. Maybe you could write one :) – CalvT Apr 17 '15 at 18:05
  • Yeah I was thinking about that. Hoped SO had the answer, Google didn't gave me an answer too. – jerone Apr 17 '15 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.