Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery's html() method auto-join the argument if it's an array?

While experimenting, I came across this.

<div id="result"></div>
<script type="text/javascript">
$('#result').html(['<p>This is inside an array</p>', '<em>This is second item in array</em>']);
</script>

When the page was reneded, I could see the following markup in the browser console:

<div id="result">
   <p>This is inside an array</p>
   <em>This is second item in array</em>
</div>

Does this mean that jQuery is running array.join("") in the background if the argument/parameter supplied to the .html() method is an array?

I couldn't find this mentioned in the documentation and hence was curious to know more on this.

like image 706
asprin Avatar asked Mar 28 '18 07:03

asprin


People also ask

What is the HTML() method in jQuery?

The html() Method in jQuery is used to set or return the innerHTML content of the selected element. Syntax: It returns the content of first matched element. $(selector).html() It sets the content of matched element. $(selector).html(content) It sets the content using function. $(selector).html(function(index, currentcontent))

What is the use of jQuery Join () method?

The jQuery join () method is a built-in method in jQuery, which is used to join all the elements of an array by a specific separator. This is a guide to jQuery join.

Do you use jQuery’s HTML function right?

You're Using jQuery.html () Wrong! Well, you probably are doing it wrong. jQuery’s html function is a very nice way to replace the contents of an element with new contents. Its usefulness is supposedly limited, though, according to the API documentation for this method.

What does htmlstring return in jQuery?

.html( htmlString )Returns: jQuery. Description: Set the HTML contents of each element in the set of matched elements. A string of HTML to set as the content of each matched element. A function returning the HTML content to set.


2 Answers

Extending @BoltClock's answer, html method's definition in jquery.js file is as below:

html: function( value ) {
    return access( this, function( value ) {
        var elem = this[ 0 ] || {},
            i = 0,
            l = this.length;

        if ( value === undefined && elem.nodeType === 1 ) {
            return elem.innerHTML;
        }

        // See if we can take a shortcut and just use innerHTML
        if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
            !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

            value = jQuery.htmlPrefilter( value );

            try {
                for ( ; i < l; i++ ) {
                    elem = this[ i ] || {};

                    // Remove element nodes and prevent memory leaks
                    if ( elem.nodeType === 1 ) {
                        jQuery.cleanData( getAll( elem, false ) );
                        elem.innerHTML = value;
                    }
                }

                elem = 0;

            // If using innerHTML throws an exception, use the fallback method
            } catch ( e ) {}
        }

        if ( elem ) {
            this.empty().append( value );
        }
    }, null, value, arguments.length );
},

So this checks for if (typeof value === "string" and when it fails it skips the portion of directly setting the value as innerHTML and if(elem) executes after making sure its an element does what is specified in @BoltClock's answer. i.e.

this.empty().append( value );

and the definition of the empty goes as

// Remove all callbacks from the list
empty: function() {
       if ( list ) {
          list = [];
        }
        return this;
},
like image 112
Guruprasad J Rao Avatar answered Oct 26 '22 22:10

Guruprasad J Rao


When passed anything other than a string, .html() empties the element and uses .append() to append the HTML instead, which, when given an array, inserts the HTML strings in the array in the order they appear. This behavior is only documented for .append().

The fact that .html() uses .empty().append() internally when passed an argument that's neither a string nor a function is not stated in its documentation page. The closest is a statement that jQuery empties the element in much the same way when given a function, although that does just follow the same .empty().append() code path.

Note that this does not actually call Array.join() in the way that you would expect. It appends elements represented by each string in the array one by one, rather than joining all the strings first before inserting it via innerHTML. So, for example, the following with a missing (optional) </p> end tag behaves identically — it does not insert a p containing an em child, but a p and an em as siblings, in that order:

$('#result').html(
  [
    '<p>This is inside an array',
    '<em>This is second item in array</em>'
  ]
);
like image 31
BoltClock Avatar answered Oct 27 '22 00:10

BoltClock