Search code examples
javascripthtmlfunctionobject-literalcreateelement

Directly put a global object to a HTML element


Here is my code :

document._createELement = document.createElement;
document.createElement = function(type, data){
    var x = document._createElement(type);
    x = data;

    return x;
}

And I tried this :

document.body.appendChild(document.createElement("p", {
    innerHTML: "Hi!"
}));

And I expect to see this in the HTML :

<p>Hi!</p>

What's the solution to complete the document.createElement function above?


Solution

  • If you are just wanting to create a p element and append to the body, this will do it

    var p = document.createElement("p");
    p.innerHTML = "Hello!";
    document.body.appendChild(p);
    

    EDIT

    Missunderstood you mean this

    function createEl(type, data) {
        var el = document.createElement(type);
        for ( var x in data ) {
          el[x] = data[x];
        };
        return el;
    }
    
    var p = createEl("p", { innerHTML : "Hi There!" });
    document.body.appendChild(p);
    

    JSFiddle