jQuery.parseHTML()


jQuery.parseHTML( data [, context ] [, keepScripts ] )Returns: Array

Description: Parses a string into an array of DOM nodes.

jQuery.parseHTML uses a native DOM element creation function to convert the string to a set of DOM elements, which can then be inserted into the document.

By default, the context is the current document if not specified or given as null or undefined. If the HTML was to be used in another document such as an iframe, that frame's document could be used.

Security Considerations

Most jQuery APIs that accept HTML strings will run scripts that are included in the HTML. jQuery.parseHTML does not run script in the parsed HTML unless keepScripts is explicitly true. However, it is still possible in most environments to execute script indirectly, for example via the <img onerror> attribute. The caller should be aware of this and guard against it by cleaning or escaping any untrusted inputs from sources such as the URL or cookies. For future compatibility, callers should not depend on the ability to run any script content when keepScripts is unspecified or false.

Example:

Create an array of Dom nodes using an HTML string and insert it into a div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.parseHTML demo</title>
<script src="//code.jquery.com/jquery-1.10.2.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>

Demo: