Home >Web Front-end >JS Tutorial >Detailed explanation of jQuery.contents() function
The
contents() function is used to select all child nodes of the current matching element (including text nodes, comment nodes, etc.) and return it in the form of a jQuery object.
This function belongs to the jQuery object (instance).
Syntax
jQuery 1.2 Added this function.
jQueryObject.contents( )
Return value
contents()The return value of the function is jQuery type and returns A new jQuery object that contains all child nodes of the element matched by the current jQuery object (including all types of nodes such as elements, text, comments, etc.).
As long as there are any whitespace characters (spaces, newlines, etc.) between two HTML tags, they will be regarded as text nodes.
If the element is an d5ba1642137c3f32f4f4493ae923989c, select all document nodes of the document.
If there is no matching element, an empty jQuery object is returned.
Example & Description
Take the following HTML code as an example:
<p id="n1"> Hello <span id="n2"> CodePlayer <span id="n3">A</span> </span> <!-- 注释内容 --> <span id="n4"> B <label id="n5"></label> </span> </p>
The following jQuery sample code is used to demonstrate the specific usage of the contents() function:
//返回jQuery对象所有匹配元素的标识信息数组 //每个元素形如:[文本内容]、[--注释内容--]或#id function getTagsInfo($doms){ return $doms.map(function(){ if(this.nodeType == 3){ // 文本节点 return "[" + this.nodeValue + "]"; }else if(this.nodeType == 8){ // 注释节点 return "[--" + this.nodeValue + "--]"; }else{ return "#" + this.id; } }).get(); } // 匹配n1元素所有的子节点(包括文本节点、注释节点等,下同) var $n1_contents = $("#n1").contents(); document.writeln( getTagsInfo( $n1_contents ) ); // [ Hello ],#n2,[ ],[-- 注释内容 --],[ ],#n4,[ ] //匹配span元素所有的子节点 var $span_contents = $("span").contents(); document.writeln( getTagsInfo( $span_contents ) ); // [ CodePlayer ],#n3,[ ],[A],[ B ],#n5,[ ] // 匹配span元素所有子节点中的非Element节点 var $span_text = $span_contents.filter( function(){ return this.nodeType != 1; } ); document.writeln( getTagsInfo( $span_text ) ); // [ CodePlayer ],[ ],[A],[ B ],[ ] //匹配n5元素所有的子节点,n5标签中没有任何内容,因此返回空的jQuery对象,匹配0个元素 var $n5_contents = $("#n5").contents(); document.writeln( $n5_contents.length ); // 0
The above is the detailed content of Detailed explanation of jQuery.contents() function. For more information, please follow other related articles on the PHP Chinese website!