html and text can get and modify the content in the DOM node as follows:
- html(value) gets the innerHTML content of an element in the matching element set, or sets the innerHTML content of each element. Value is optional, which can be an html code or a function that returns html code. If there is no parameter, the innerHTML content of the first element in the matching element set is obtained
- text(text) gets the combined text content of all elements in the matching element collection, or sets the text content of each element, encapsulating the createTextNode method
writer by: Desert QQ:22969969
Here's a chestnut:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://libs.baidu.com/jquery/1.7.1/jquery.min.js"></script> </head> <body> <div>Hello World!</div> <button id="b1">Button 1</button> <button id="b2">Button 2</button> <script> $('#b1').click(()=>{ $('div').html('<p>Hello jQuery!</p>') //Use html()Set value }) $('#b2').click(()=>{ $('div').text('<p>Hello jQuery!</p>') //Use text()Set value }) </script> </body> </html>
Render as follows:
Click button 1 to use html() to set the value, and the rendering is as follows:
Click button 2 to set the value with text(), and the rendering is as follows:
It can be seen that for html(), the meaning of the inner tag is parsed out, while for text(), it is simply displayed, because the former is realized by setting innerHTML, and the latter is realized by creating a text node created by createTextNode
Source code analysis
For html, it is implemented through innerHTML as follows:
jQuery.fn.extend({ html: function( value ) { //Gets the HTML Content, or set the HTML Content. By reading, setting innerHTML To achieve. value Optional, can be html Code or return html Function of the code. if ( value === undefined ) { //If no parameters are passed in, the HTML content return this[0] && this[0].nodeType === 1 ? //If this[0]Exists and is an element node this[0].innerHTML.replace(rinlinejQuery, "") : //read innerHTML attribute null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) && //html Is a code code and does not contain script or style Label. (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && //The browser does not ignore leading whitespace negatives, or html Code does not start with a blank character. !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { //html Tags in code can be serialized correctly without wrapping the parent tag value = value.replace(rxhtmlTag, "<$1></$2>"); //Correction of self closing label try { for ( var i = 0, l = this.length; i < l; i++ ) { //Traverse the current matching element // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { //If the node is an element node jQuery.cleanData( this[i].getElementsByTagName("*") ); //Remove all data and events associated with descendant elements first this[i].innerHTML = value; //attemptSet properties directly innerHTML insert HTML Content. } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); //If you are setting innerHTML If there is an exception, call first empty()Removes data and events associated with offspring elements, removes subelements, and then calls.append()Insert new content. } } else if ( jQuery.isFunction( value ) ) { //If value If it is a function, it will traverse the set of matching elements, execute the function on each element, and take its return value as the new html Content, iterative call.html(vlue). this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; //Last return this,To support chain operation }, })
For text, it is implemented by the text node created by createTextNode, as follows:
jQuery.fn.extend({ text: function( text ) { //Get the combined text content of all elements in the matching element collection, or set the text content of each element through createText()Method to create a text node and append()Get in. if ( jQuery.isFunction(text) ) { //If text If it is a function, execute the function on each matching element, take its return value as the new text content, and call iteratively.text(text)Method. return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); //Set keywords when calling functions this Execute the current element with two parameters passed in:The subscript position of the current element in the collection, the old text content of the current element. }); } if ( typeof text !== "object" && text !== undefined ) { //If parameters text It's not an object. It's not an object undefined,That is, it could be a string, a number, or a Boolean value. return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); //Empty the content first, then create a text node and insert it into each matching element } return jQuery.text( this ); //If there are no incoming parameters or parameters text Wrongful(object),Then call jQuery.text(elem)Get the combined text content of all matching elements(sizzle Selector). }, })
Relatively simple