Search code examples
javascriptobjectcreateelement

How would I assign n number of properties to an object depending on the given parameters in a function?


I am making a more simple way of document.createElement function, and this is what I have so far.

function createEl(type, parent) {
    var element = document.createElement(type);
    parent.appendChild(element);
}

The problem I have is I don't know how to make it so that I can add use the argumments, and using the parameter, you can assign any number of properties to the element object I have created inside the function. For example, if you wanted to add one that determined element's absolute style. I'm thinking it should have to do Object.assign, but I'm not exactly sure.


Solution

  • You can pass objects, one for attributes and one for style:

    function createEl(type, parent, attributes, style) {
        var element = document.createElement(type);
        //add attributes
        Object.entries(attributes).forEach(([attributeName, attributeValue]) => {
            element.setAttribute(attributeName, attributeValue);
        });
        //add style 
        Object.entries(style).forEach(([styleProp, styleValue]) => {
            console.log(styleProp+ styleValue);
            element.style[styleProp] = styleValue;
        });
        domElement = document.getElementById(parent);
        domElement.appendChild(element);
    }   
    

    and call the function with:

        const type = "div";
        const parent = "test";
        const attributes = {"id" : "div1" , "class" : "redButton", "..." : "..."};
        const style = {"position" : "absolute", "color" : "green" , "..." : "..."};
        createEl(type, parent, attributes, style);
    

    You can set any sort of attriubutes and style properties