Search code examples
javascriptobjectargumentscreateelement

Creating one element with arguments taken from the object - JavaScript


I want to create a function that gets data from an array and creates the appropriate tags in HTML + the appropriate argument. The problem occurs when there is more than one argument.

Creation logs IMG

They form but not together only separately.

var elem = [[
    // <div class"container"></div> //Example
    ["div", "container"],
    ["form", {method: "POST", name: "contant"}], //Two objects (arguments for html)
    ["div", "box"]
]];
class Form {
    constructor(index) {
        this.index = index;
    };

    createField() {
        for(const marker of elem[this.index]) {
            if(marker[1] instanceof Object) {
                for(var test of Object.keys(marker[1])) {
                    console.log(this.createElement(marker[0], {
                        [test]: marker[1][test]
                    }));
                }
            } else { //If there is no object, it adds a class
                var key = 'class';
                var value = marker[1]
                console.log(this.createElement(marker[0], {
                    [key]: value
                }));
            }
        };
    };

    createElement(elementName, attributes) {
        this.element = this.createElement.call(document, elementName);

        if(attributes && !(attributes instanceof Object)) {
            throw Error('Error attributes');
        } else if(attributes) {
            for(const attr of Object.keys(attributes)) {
                this.element.setAttribute(attr, attributes[attr]);
            };
        };
        return this.element;
    };

I would like to make this have these two arguments in it, and not be created twice from one argument


Solution

  • You're passing the attributes individually, just use the whole object.

          if(marker[1] instanceof Object) {
    
                console.log(this.createElement(marker[0], marker[1]));
            }