jQuery.parseHTML()Method

jQuery 杂项方法jQuery Miscellaneous Methods

Example

Use an HTML string to create an array of DOM nodes and insert it into a div.

<div id="log"> <h3>Content:</h3> </div> <script> $(function () { var $log = $( "#log" ), str = "hello, <b>my name is</b> jQuery.", html = $.parseHTML( str ), nodeNames = []; //Add parsed HTML $log.append( html ); //Collect the node names of the parsed HTML $.each( html, function( i, el ) { nodeNames[i] = "<li>" + el.nodeName + "</li>"; }); //Insert node names $log.append( "<h3>Node Names:</h3>" ); $( "<ol></ol>" ) .append( nodeNames.join( "" ) ) .appendTo( $log ); }) </script>

Try it Yourself »

Definition and Usage

$.parseHTML() function is used to parse an HTML string into an array of corresponding DOM nodes.

Note:1. This function will use the native DOM element creation function to convert an HTML string into a collection of DOM elements, and you can insert these DOM elements into the document.
2. If the context parameter is not specified, or it is null or undefined, it defaults to the current document. If the created DOM elements are intended for another document, such as an iframe, you should specify that iframe's document object.
Security Considerations:Most jQuery APIs allow HTML strings to include running scripts in the HTML. jQuery.parseHTML() does not run scripts in the parsed HTML unless you explicitly set the keepScripts parameter to true. However, most environments can still execute scripts indirectly, for example, throughattributes. Callers should avoid doing so, and clean or escape any untrusted input from sources such as URLs, cookies, etc., to prevent this situation from occurring. For future compatibility, when the keepScripts parameter 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 be parsed and converted into an array of DOM nodes.
context Element type - Specifies the Document in which to create elements, defaults to the current document's document object.
keepScripts Boolean type - Specifies whether the passed HTML string contains scripts, defaults to false.


jQuery 杂项方法jQuery Miscellaneous Methods

Other Extensions