jQuery parseHTML() example

jQuery parseHTML() function is used to parses a string into an array of DOM nodes.

Syntax

jQuery.parseHTML( data [, context ] [, keepScripts ] )
  • data - HTML string to be parsed 
  • context (default: document) - Document element to serve as the context in which the HTML fragment will be created 
  • keepscripts (default: false) - A Boolean indicating whether to include scripts passed in the HTML string

Example

Create an array of DOM nodes using an HTML string and insert it into a div.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>jQuery.parseHTML demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <div id="log">
        <h3>Content:</h3>
    </div>

    <script>
        var $log = $("#log"),
            str = "hello, <b>my name is</b> jQuery.",
            html = $.parseHTML(str),
            nodeNames = [];

        // Append the parsed HTML
        $log.append(html);

        // Gather the parsed HTML's node names
        $.each(html, function(i, el) {
            nodeNames[i] = "<li>" + el.nodeName + "</li>";
        });

        // Insert the node names
        $log.append("<h3>Node Names:</h3>");
        $("<ol></ol>")
            .append(nodeNames.join(""))
            .appendTo($log);
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References

Comments