Razib Razib - 1 month ago 9
Javascript Question

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

I'm now working with some

javascript
and trying to set a text in a
span
like this -

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


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

Answer

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