JavaScript替代jQuery的html()方法

5
你会如何编写这个jQuery方法?
$('body').html(node); 

在JavaScript中设置节点的HTML内容怎么做?谢谢。
7个回答

17

4

如果node是DOM节点而不是HTML字符串,您应该使用DOM方法而不是innerHTML

while (document.body.firstChild) {
    document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(node);

See MDC docs:


2
你正在寻找innerHTML属性:
document.getElementById("test").innerHTML = "";

1

对于比仅设置正文更一般的情况...

// 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");

1

供参考,这是jQuery的做法:

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;
},

它尽可能使用innerHTML,但也具备备用方法。


1
如果您想将HTML插入到body标签中,请尝试以下方法:
document.body.innerHTML = node;

或者

document.getElementsByTagName('body')[0].innerHTML = node;

1

document.body.innerHTML = '我的 HTML 在这里';


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接