How would you write this jQuery method
$('body').html(node);
for setting html to node in Javascript?
thank you
Yes thats possible:
document.body.innerHTML="<h1>Hello World</h1>";
If node is a DOM node rather than an HTML string, you should use DOM methods instead on innerHTML:
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(node);
See MDC docs:
You are looking for the innerHTML property:
document.getElementById("test").innerHTML = "";
And for the more general case than just setting the body....
// replace a single element by its ID
// i.e. $("#myDivId")
var myDiv = document.getElementById("myDivId");
myDiv.innerHtml = "foo";
// replace all elements of a given tag name
// i.e. $("span")
var allSpanTags = document.getElementsByTagName("span");
allSpanTags[0].innerHtml = "foo"; // or loop over the array or whatever.
// by class name
// i.e. $(".myClass")
var allMyClass = document.getElementsByClassName("myClass");
For reference, here's the way that jquery does it:
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
It uses innerHTML when it can, but it also has a fallback method.