Proseller
Proseller

Reputation: 101

Adding a class to a created element

The parameter of my function is a function. It should create an element but I should still be able to add attributes by using the parameter details.

E.g.:

const addElement = (details) => {
    const element = document.createElement('div');
}

addElement(function() {
    element.id = 'my-div'; // Not working since element is not defined
});

Well, I have tried to store the element in an object to be able to use it outside of that function.

let element = {};
const displayVideo = (type, details) => {
    element = document.createElement(type);
    element.width = 200;
    element.height = 200;
    element.classList.add('my-class'); // <--- THE PROBLEM!
    if (details) {
        details();
    }
    document.querySelector('#layer').insertBefore(element, document.querySelector('#el'));
};

displayVideo('VIDEO', function () {
    element.controls = true;
});

My element can not be created because of element.classList.add('my-class'); and I don't even get an error message. If I remove that line, it works but I would still like to be able to add a class to that object. How can I do this?

Upvotes: 0

Views: 62

Answers (2)

Samathingamajig
Samathingamajig

Reputation: 13245

Just pass element into the function. Since you're just editing properties on the object, this won't cause reference vs value errors.

const addElement = (details) => {
    const element = document.createElement('div');
    if (details) details(element);
    return element;
}

const ele = addElement(function(element) {
    element.id = 'my-div';
});

console.log(ele);

Upvotes: 3

drake7
drake7

Reputation: 1214

In this case details could be something like classname.

function element(type, classname) {

    var element = document.createElement(type);
    
    if (classname !== undefined) {
        element.classList.add(classname);
    }
    
    return element;
};

element("div","my-class"); //<div class="my-class"></div>

Of course instead of classname you could use an array or an object and loop through in order to set multiple attributes.

Or you could store the return value of your function in a variable and then add all the attributes:

var myelement = element("div");
myelement.classList.add("my-new-class");
myelement //<div class=​"my-new-class">​</div>​

Upvotes: 0

Related Questions