{"id":1747,"date":"2013-01-11T19:06:50","date_gmt":"2013-01-12T00:06:50","guid":{"rendered":"http:\/\/www.rexfeng.com\/blog\/?p=1747"},"modified":"2013-01-11T19:06:50","modified_gmt":"2013-01-12T00:06:50","slug":"how-jquery-text-method-works-in-javascript","status":"publish","type":"post","link":"https:\/\/www.rexfeng.com\/blog\/2013\/01\/how-jquery-text-method-works-in-javascript\/","title":{"rendered":"How jQuery text method works in JavaScript"},"content":{"rendered":"<p><a href=\"http:\/\/jquery.com\/\">jQuery<\/a> has a popular method for accessing the text contents of a targeted DOM node named [cci].text()[\/cci]. It allows you to either get the text content or set the text content.<\/p>\n<p>For example, using [cci]text()[\/cci] on [cci]$(&#8216;#test&#8217;)[\/cci] returns [cci]foobar[\/cci] below:<br \/>\n[cc]<\/p>\n<div id=\"test\"><span>foobar<\/span><\/div>\n<p>    $(&#8216;#test&#8217;).text(); \/\/=> returns &#8216;foobar&#8217;<br \/>\n[\/cc]<\/p>\n<p>By using [cci]text()[\/cci] with a parameter, you can set the text to the passed in parameter.<br \/>\n[cc]<\/p>\n<div id=\"test\"><span>foobar<\/span><\/div>\n<p>    $(&#8216;#test&#8217;).text(&#8220;cupcakes&#8221;); \/\/ sets the value to &#8216;cupcakes&#8217;<br \/>\n    $(&#8216;#test&#8217;).text(); \/\/=> returns &#8216;cupcakes&#8217;<br \/>\n[\/cc]<\/p>\n<p>There is a similar jQuery method named [cci]html()[\/cci]. It returns the html contents within the targeted DOM node.<br \/>\n[cc]<\/p>\n<div id=\"test\"><span>foobar<\/span><\/div>\n<p>    $(&#8216;#test&#8217;).html(); \/\/=> returns &#8216;<span>foobar<\/span>&#8216;<br \/>\n[\/cc]<\/p>\n<p>Before we dive into the jQuery source, we can guess that jQuery uses <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/DOM\/Node.textContent\">textContent<\/a>.<\/p>\n<p>In the <a href=\"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1\/jquery.js\">jQuery source<\/a>, you can see on line 5702:<br \/>\n[cc]<br \/>\n    jQuery.fn.extend({<br \/>\n      text: function( value ) {<br \/>\n        return jQuery.access( this, function( value ) {<br \/>\n          return value === undefined ?<br \/>\n            jQuery.text( this ) :<br \/>\n            this.empty().append( ( this[0] &#038;&#038; this[0].ownerDocument || document ).createTextNode( value ) );<br \/>\n        }, null, value, arguments.length );<br \/>\n      },<br \/>\n[\/cc]<\/p>\n<p>jQuery checks the passed in parameter [cci]value[\/cci] using a ternary operator. If [cci]value[\/cci] is [cci]undefined[\/cci], then jQuery calls [cci]text[\/cci]. Else, jQuery sets the value with [cci]createTextNode[\/cci].<\/p>\n<p>[cci]jQuery.access[\/cci] on line 784 allows <a href=\"http:\/\/stackoverflow.com\/questions\/12857960\/strange-behaviour-of-jquery-attr-method\">jQuery to determine if the value is defined or undefined<\/a>.<\/p>\n<p>If undefined, [cci]jQuery.text( this )[\/cci] runs.<\/p>\n<p>[cc]<br \/>\n    \/\/ line 5348:<br \/>\n    jQuery.text = Sizzle.getText;<br \/>\n[\/cc]<\/p>\n<p>Sizzle&#8217;s getText looks like:<\/p>\n<p>[cc]<br \/>\n    \/**<br \/>\n     * Utility function for retrieving the text value of an array of DOM nodes<br \/>\n     * @param {Array|Element} elem<br \/>\n     *\/<br \/>\n    getText = Sizzle.getText = function( elem ) {<br \/>\n      var node,<br \/>\n        ret = &#8220;&#8221;,<br \/>\n        i = 0,<br \/>\n        nodeType = elem.nodeType;<\/p>\n<p>      if ( nodeType ) {<br \/>\n        if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {<br \/>\n          \/\/ Use textContent for elements<br \/>\n          \/\/ innerText usage removed for consistency of new lines (see #11153)<br \/>\n          if ( typeof elem.textContent === &#8220;string&#8221; ) {<br \/>\n            return elem.textContent;<br \/>\n          } else {<br \/>\n            \/\/ Traverse its children<br \/>\n            for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {<br \/>\n              ret += getText( elem );<br \/>\n            }<br \/>\n          }<br \/>\n        } else if ( nodeType === 3 || nodeType === 4 ) {<br \/>\n          return elem.nodeValue;<br \/>\n        }<br \/>\n        \/\/ Do not include comment or processing instruction nodes<br \/>\n      } else {<\/p>\n<p>        \/\/ If no nodeType, this is expected to be an array<br \/>\n        for ( ; (node = elem[i]); i++ ) {<br \/>\n          \/\/ Do not traverse comment nodes<br \/>\n          ret += getText( node );<br \/>\n        }<br \/>\n      }<br \/>\n      return ret;<br \/>\n    };<br \/>\n[\/cc]<\/p>\n<p>You can see that jQuery either returns the string with [cci]textContent[\/cci]<\/p>\n<p>[cc]<br \/>\n    \/\/ Use textContent for elements<br \/>\n    \/\/ innerText usage removed for consistency of new lines (see #11153)<br \/>\n    if ( typeof elem.textContent === &#8220;string&#8221; ) {<br \/>\n      return elem.textContent;<br \/>\n    }<br \/>\n[\/cc]<\/p>\n<p>or jQuery will traverse the DOM and append them into the [cci]ret[\/cci] variable (initialized as as empty string) to return.<\/p>\n<p>[cc]<br \/>\n    \/\/ Traverse its children<br \/>\n    for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {<br \/>\n      ret += getText( elem );<br \/>\n    }<br \/>\n[\/cc]<\/p>\n<p>If you are passing in a param value into [cci]text()[\/cci], then jQuery will empty out the contents of the targeted DOM node and use <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/DOM\/document.createTextNode\">createTextNode<\/a> to allow your passed in param to show up.<\/p>\n<p>[cc]<br \/>\n    this.empty().append( ( this[0] &#038;&#038; this[0].ownerDocument || document ).createTextNode( value ) );<br \/>\n[\/cc]<\/p>\n<p>If you are interested in using Core JavaScript to replicate jQuery&#8217;s [cci]text()[\/cci], you could try the following:<\/p>\n<p>[cc]<\/p>\n<div id=\"test\">lion<\/div>\n<p>    var div = document.querySelectorAll(&#8220;#test&#8221;);<br \/>\n    div[0].textContent; \/\/=> returns &#8216;lion&#8217;<br \/>\n[\/cc]<\/p>\n<p>This targets the [cci]#test[\/cci] div and get the text content.<\/p>\n<p>[cc]<\/p>\n<div id=\"test\"><\/div>\n<p>    var div = document.querySelectorAll(&#8220;#test&#8221;);<br \/>\n    div[0].appendChild(document.createTextNode(&#8216;pizza&#8217;));<br \/>\n[\/cc]<\/p>\n<p>This is one way to set the div contents to display &#8216;pizza&#8217;.<\/p>\n<p>Thanks for tuning into to another jQuery without jQuery. Diving into the <a href=\"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1\/jquery.js\">source code<\/a> is great for helping you understand how it all works.<\/p>\n<p><em><a href=\"http:\/\/www.rexfeng.com\/blog\/tag\/jquerywithoutjquery\/\">jQuery without jQuery<\/a> is a series that aims to open up the <a href=\"http:\/\/jquery.com\/\">jQuery<\/a> black box. jQuery is just JavaScript, so you should feel comfortable  working at lower levels of abstraction and looking at the <a href=\"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1\/jquery.js\">jQuery source code<\/a> written in JavaScript.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>jQuery has a popular method for accessing the text contents of a targeted DOM node named [cci].text()[\/cci]. It allows you to either get the text content or set the text content. For example, using [cci]text()[\/cci] on [cci]$(&#8216;#test&#8217;)[\/cci] returns [cci]foobar[\/cci] below: [cc] foobar $(&#8216;#test&#8217;).text(); \/\/=> returns &#8216;foobar&#8217; [\/cc] By using [cci]text()[\/cci] with a parameter, you can [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1029],"tags":[1024,1046,1023,1054,1053,1059],"class_list":["post-1747","post","type-post","status-publish","format-standard","hentry","category-programming","tag-html","tag-javascript","tag-jquery","tag-js","tag-sizzle","tag-text"],"_links":{"self":[{"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/posts\/1747","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/comments?post=1747"}],"version-history":[{"count":9,"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/posts\/1747\/revisions"}],"predecessor-version":[{"id":1756,"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/posts\/1747\/revisions\/1756"}],"wp:attachment":[{"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/media?parent=1747"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/categories?post=1747"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.rexfeng.com\/blog\/wp-json\/wp\/v2\/tags?post=1747"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}