Aaron Etheridge
Aaron Etheridge

Reputation: 93

Trying to set multiple Attributes at the same time

Is there a good way to set multiple attributes with a function, I have found a prototype to Elements that takes attribute arguments but I still have to write out everything inside when I call the method. I'm not sure how to or if it is possible to create a temporary empty element.

Element.prototype.setAttributes = function (attrs) {
    for (var idx in attrs) {
        if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
            for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
        } else if (idx === 'html') {
            this.innerHTML = attrs[idx];
        } else {
            this.setAttribute(idx, attrs[idx]);
        }
    }
};

This method takes input like below

div.setAttributes({     //// This Works
        'id' :  'my_div',
        'class' : 'my_class'
    });

and returns div with the added Attributes.

I am trying to use the above prototype to make a new function that allows me to add attributes without having to plug in something like 'class' : 'my_class'.

I would like to be able to do below

div.inputSet("my_id","my_class");

Below is what I have tried, I'm not sure if this is possible. I have 2 days of javascript experience.

Element.prototype.inputSet = function(ids, classs, types, placeholders){
        var temp: new Element; ///// How to Create an empty element???
        return temp.setAttributes({
            'id' : `${ids}`,
            'class' : `${classs}`,
            'type'  : `${types}`,
            'placeholder' : `${placeholders}`
        });
    };

I would like to return an element with the attributes args passed into the function.

Upvotes: 2

Views: 3301

Answers (1)

Mauricio Sipmann
Mauricio Sipmann

Reputation: 475

Kind of hard to understand what you're asking but.. it's something like the following snip? What I don't understand is why you're trying to create a new Element..

Element.prototype.setAttributes = function (attrs) {
    for (var idx in attrs) {
        if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
            for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
        } else if (idx === 'html') {
            this.innerHTML = attrs[idx];
        } else {
            this.setAttribute(idx, attrs[idx]);
        }
    }
};

Element.prototype.inputSet = function(ids, classs, types, placeholders){
        // just like your "setAttributes" method... use the This to set the attributes
        return this.setAttributes({
            'id' : `${ids}`,
            'class' : `${classs}`,
            'type'  : `${types}`,
            'placeholder' : `${placeholders}`
        });
    };
document.querySelector('#sample').inputSet('abc', 'for');
.for {
 border:1px solid red;
 width:100px;
 height: 100px;
}
<div id="sample"></div>

Upvotes: 2

Related Questions