Razib Razib - 1 year ago 58
Javascript Question

How jquery $('#some_id').text('some_text') works?

I'm now working with some

and trying to set a text in a
like this -

<span id='span_id'></span>
<script type='text/javascript'>
$('#span_id').text('Hello World');

So far I know to change/set some value/text on an html page without reloading it we have to use
. I'm wondering how does this -
$('#span_id').text('Hello World')
works here without reloading the page

Answer Source

Here is the source from jQuery (specifically manipulation.js) where the function is defined:

text: function( value ) {
    return access( this, function( value ) {
        return value === undefined ?
            jQuery.text( this ) :
            this.empty().each( function() {
                if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
                    this.textContent = value;
            } );
    }, null, value, arguments.length );


It's just defining the textContent attribute on the selected node. This is triggering a reflow/repaint event (as new text will take up a new amount of space) but not a full page reload. You can read up on what the nodeType values mean here: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download