jQuery.parseHTML() method
Example
Create an array of DOM nodes from an HTML string and insert it into a div
<div id="log">
<h3 Content>:
h3
div
<script$(function(){var$log>= $
(
"
#log
"
)
,
str
=
"
hello, my name is jQuery.
"
,
html
= $.
parseHTML
(
str
)
,
nodeNames
=
[
]
;
//
Add the parsed HTML
$
log
.
append
(
html
)
;
//
Collect the node names of the parsed HTML
$.
each
(
html
,
function
(
i
,
el
)
{
nodeNames
[
i
]
=
"
"
el
.
nodeName
"
"
;
}
)
;
//
Insert the node names
$
log
.
append
(
"
Node Names:
"
)
; $
(
"
"
)
.
append
(
nodeNames
.
join
(
"
"
)
)
.
appendTo
(
$
log
)
;
}
)
script
Try it »
Definition and Usage
The $.parseHTML() function is used to parse an HTML string into a corresponding array of DOM nodes.
**Note:** 1. This function uses the native DOM element creation function to convert an HTML string into a collection of DOM elements, which you can insert into the document.
2. If the context argument is not specified, or is null or undefined, it defaults to the current document. If the created DOM elements are to be used in another document, such as an iframe, you should specify that iframe's document object.
**Security considerations:** Most jQuery APIs allow HTML strings to contain running scripts within the HTML. jQuery.parseHTML() does not run scripts in the parsed HTML unless you explicitly set the keepScripts argument to true. However, most environments can still execute scripts indirectly, for example throughattributes. Callers should avoid doing this and should sanitize or escape any untrusted input from sources such as URLs and cookies to prevent this. For future compatibility, when the keepScripts argument is omitted or false, callers should not rely on any ability to run script content.
Syntax
$
.parseHTML( htmlString [, context ] [, keepScripts ] )
Parameters Description htmlString String type: The HTML string to parse and convert into an array of DOM nodes context Element type: Specifies the document in which to create the elements, defaulting to the current document keepScripts Boolean type: Specifies whether the incoming HTML string contains scripts, defaulting to false
jQuery Miscellaneous Methods