hendr1x
hendr1x

Reputation: 1501

Vanilla JS : appendChild not working but innerHTML does [simple example]

In my example code innerHTML is working perfectly but not appendChild. Can anyone explain why?

function framework(selector) {
    if (window === this) { return new framework(selector); }

    if (selector === 'document') { this.element = [document]; }
    else if (selector === 'window') { this.element = [window]; }
    else if (selector) { this.element = document.querySelectorAll(selector); }

    return this;
};
framework.prototype.append = function(node){
    if (this.element[0]){ this.element[0].appendChild = node; }
    return this;
};
framework.prototype.html = function(node){
    if (this.element[0]){ this.element[0].innerHTML = node; }
    return this;
};


var div = document.createElement('div');
div.innerHTML = 'test append';
framework("#example1").append(div);
framework("#example2").html('test html');
<div id="example1"></div>
<div id="example2"></div>

Upvotes: 1

Views: 356

Answers (2)

charlieyin
charlieyin

Reputation: 411

appendChild should take an argument. This should work:

  function framework(selector) {
        if (window === this) { return new framework(selector); }
    
        if (selector === 'document') { this.element = [document]; }
        else if (selector === 'window') { this.element = [window]; }
        else if (selector) { this.element = document.querySelectorAll(selector); }
    
        return this;
    };
    framework.prototype.append = function(node){
        if (this.element[0]){ this.element[0].appendChild(node); }
        return this;
    };
    framework.prototype.html = function(node){
        if (this.element[0]){ this.element[0].innerHTML(node); }
        return this;
    };
    
    
    var div = document.createElement('div');
    div.innerHTML = 'test append';
    framework("#example1").append(div);
    framework("#example2").html('test html');

Upvotes: 1

Dan Knights
Dan Knights

Reputation: 8368

appendChild is a method whereas innerHtml is a property. So, as with all methods, the syntax is appendChild(node).

Upvotes: 1

Related Questions