Why does jQuery.html () accept a jQuery object successfully even though the docs say it can't?
I'm just trying to figure out how it works because I have a bug in my code that might be due to a misunderstanding of mine.
docs say the parameter htmlString
.html(htmlString)
can be htmlString
either function
, but if I do this
var $div = $("div").detach();
$("body").html($div);
the highlighted div correctly
replaces the body content even if it $div
is a jQuery object.
For completeness, my complete code is below
<html>
<body style="font-size:25px">
<div><p> CLICK TO TEST </p></div>
<script src="/js/jquery-1.11.1.min.js"></script>
<script>
$(function() {
$("p").click(function() { console.log("P1 CLICKED!"); });
var $div = $("div").detach();
$("body").html($div);
//$("body").html($div);
});
</script>
</body>
</html>
Thank!
source to share
As I said in the comment, we cannot answer your direct question as we are not the one who writes the document, but I can show you why it works.
As you can see on this line , jQuery checks if the passed value is a string. If so, it does some substitution to make valid HTML, then if
close .
So, no matter what you pass as an argument, it runs these lines :
if ( elem ) {
this.empty().append( value );
}
As you know, .append()
accept a string, DOM element or jQuery object. Hence, therefore, it works. .html
doesn't really check if the argument is a string.
source to share
In short, if not a string or a function, it forwards the passed argument jQuery.fn.append
, which accepts DOM or JQuery objects . append This is why your code works.
Below is an abbreviated version of the function for clarity.
html: function( value ) {
if ( value === undefined ) {
...
} else if ( typeof value === "string" && ..... ) {
...
} else if ( jQuery.isFunction( value ) ) {
...
} else {
this.empty().append( value );
}
return this;
}
source to share