Home > Article > Web Front-end > Detailed explanation of jQuery.parseHTML() function
Definition and usage
$.parseHTML() function is used to parse HTML strings into corresponding DOM node arrays.
Note:
1. This function will use the native DOM element creation function to convert the HTML string into a collection of DOM elements. You can insert these DOM elements into the document.
2. If the context parameter is not specified, or the parameter is null or undefined, it defaults to the current document. If you create a DOM element for use in another document, such as an iframe, you should specify the document object of that iframe.
Security considerations: Most jQuery APIs allow HTML strings to be included in HTML to run scripts. jQuery.parseHTML() will not run scripts in the parsed HTML unless you explicitly specify the keepScripts parameter to true. However, most environments can still execute scripts indirectly, for example through properties. Callers should avoid doing this and sanitize or escape any untrusted input from sources such as URLs, cookies, etc. to prevent this situation. For future compatibility reasons, callers should not rely on any ability to run script content when the keepScripts parameter is omitted or false.
Syntax
$.parseHTML(htmlString [, context] [, keepScripts])
##ExampleUsage 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, <b>my name is</b> jQuery.", html = $.parseHTML( str ), nodeNames = []; //添加已解析的HTML $log.append( html ); //集合已解析HTML的节点名称 $.each( html, function( i, el ) { nodeNames[i] = "<li>" + el.nodeName + "</li>"; }); // 插入节点名 $log.append( "<h3>Node Names:</h3>" ); $( "<ol></ol>" ) .append( nodeNames.join( "" ) ) .appendTo( $log ); }) </script>Example & DescriptionThe following is done with jQuery. jQuery sample code related to the parseHTML() function to demonstrate the specific usage of the jQuery.parseHTML() function:
// "<\/script>"必须通过\将/转义,否则JS会认为已经到了脚本结束的位置 var html = 'Hello,<b>CodePlayer</b><script type="text/javascript">alert("执行脚本代码");<\/script>'; var doms = $.parseHTML( html ); // 不会执行脚本代码 $("#n1").append(doms); alert("分割线"); doms = $.parseHTML( html, true ); // 会执行脚本代码 $("#n1").append(doms);Return valuejQuery The return value of the .parseHTML() function is of Array type and returns an array of DOM nodes after parsing the specified HTML string.