jQuery.parseHTML()

jQuery

jQuery.parseHTML()


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

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

  • version added: 1.8jQuery.parseHTML( data [, context ] [, keepScripts ] )

    • data
      Type: String
      HTML string to be parsed
    • context (default: document)
      Type: Element
      DOM element to serve as the context in which the HTML fragment will be created
    • keepScripts (default: false)
      Type: Boolean
      A Boolean indicating whether to include scripts passed in the HTML string

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.

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
                                  
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.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>