You can use a DOMParser, like so:

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from maerics on Stack Overflow
🌐
PixelsTech
pixelstech.net › home › articles › convert html to dom elements using javascript
Convert HTML to DOM elements using JavaScript | PixelsTech
August 19, 2017 - Two primary methods facilitate this transformation: DOMParser and document.createElement. DOMParser parses an HTML string into a DOM Document, allowing standard DOM operations, though it's an experimental feature with limited old browser support.
🌐
GitHub
github.com › Damian96 › html-to-dom
GitHub - Damian96/html-to-dom: An HTML to Javascript DOM converter · GitHub
An HTML to Javascript DOM converter · HTML to DOM Github Page · v1.0.0 - First release · v1.1.0 - Second release ·
Author: Damian96
🌐
Krasimirtsonev
krasimirtsonev.com › blog › article › Convert-HTML-string-to-DOM-element
Convert HTML string to DOM element
June 11, 2013 - Convert HTML string to DOM element / Checkout Revealing the magic: How to properly convert HTML string to a DOM element article. I'm working on a chrome extension which accepts user text, work with it and output the result in a div. I used jQuery in the beginning, for several tasks, but later ...
🌐
YouTube
youtube.com › watch
How to Convert HTML String to DOM in Javascript - YouTube
In this video, you will learn how to convert a HTML string to DOM representation and extract some information. In the example, we will use DOMParser class to...
Published: April 11, 2024
🌐
GitHub
github.com › TimBeyer › html-to-vdom
GitHub - TimBeyer/html-to-vdom: Converts an HTML string into a virtual DOM · GitHub
June 14, 2017 - Converts an HTML string into a virtual DOM. Contribute to TimBeyer/html-to-vdom development by creating an account on GitHub.
Author: TimBeyer
🌐
Go Make Things
gomakethings.com › converting-a-string-into-markup-with-vanilla-js
Converting a string into markup with vanilla JS | Go Make Things
August 13, 2019 - Today, we’re going to look at how to take an HTML string and convert it into actual markup. If you wanted to inject a string into the DOM, you can do that pretty simply with innerHTML.
Find elsewhere
🌐
Hixie
software.hixie.ch › utilities › js › live-dom-viewer
Live DOM Viewer
This script puts a function w(s) into the global scope of the test page, where s is a string or object to output to the log
🌐
Medium
medium.com › @fulit103 › converting-html-to-a-virtual-dom-in-javascript-3a6db0f563b1
Converting HTML to a Virtual DOM in JavaScript | by Julian Toro | Medium
December 18, 2022 - In this article, we’ll look at how to create a virtual DOM from an HTML string using the DOMParser API and a recursive function.
🌐
David Walsh
davidwalsh.name › convert-html-stings-dom-nodes
Convert String to DOM Nodes
March 20, 2017 - The DOMParser API allows developers to create DOM nodes from and HTML string using JavaScript.
Top answer
1 of 2
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>
2 of 2
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.

🌐
npm
npmjs.com › package › html-dom-parser
html-dom-parser - npm
August 13, 2026 - The parser converts an HTML string to a JavaScript object that describes the DOM tree.
      » npm install html-dom-parser
    
Published: Aug 13, 2026
Version: 8.0.2
🌐
Stack Overflow
stackoverflow.com › questions › 21423437 › is-there-any-program-or-library-to-convert-html-to-dom-mainpulation-script
Is there any program or library to convert html to dom mainpulation script?
@Yani Yes, but as it's responsive and jQuery's dom maipulation performance is TOO slow for mobile, especially android. ... @HackerK If you want higher performance, then why are you seeking a 3rd party lib. Better do this with vanilla JS ... @PraveenJeganathan I want to pre-compile(?) html to pure javascript manipulation code for better performance, and easier developement
🌐
Tcl Wiki
wiki.tcl-lang.org › page › HTML+to+DOM+via+http › htmlparse › struct::tree+packages
HTML to DOM via http/htmlparse/struct::tree packages
So I tried successfully to use htmlparse, which uses struct::tree to store the parsed data in. So I use the struct::tree routines to convert its data into a tDOM DOM tree.
🌐
Wtools
wtools.io › html-to-javascript-converter
Online HTML to JavaScript Converter - wtools.io
Free tool for online converting HTML code to JavaScript variable or using write, writeln statements.