Search code examples
javascriptpropertiescreateelement

javascript createElement with property


I'm trying to add a element from Javascript with classname person.

It works perfectly fine by below code.

const element = document.createElement('div');
element.classList.add('person');

But why the below not working?

const element = document.createElement('div').classList.add('person');

Solution

  • document.createElement() returns an element, but calling .classList.add on an element doesn't return that same element.

    In your first code, element becomes a newly created element. Then on the next line, you call its .classList.add() method to add a class to that element. The element variable itself was never changed, but .classList.add() changed some internal property of element.

    In your second code, you create a new element with document.createElement(), then immediately call .classList.add() to add a class to that element. Then .classList.add() doesn't return anything, so the element variable has the value undefined. Variables are only assigned the last value returned by a function when chaining functions together.

    If you really wanted to make the last one work, then you'd need to create a new function that calls .classList.add() then returns the element, like this:

    function addClass(el, className) {
      el.classList.add(className);
      return el;
    }
    
    const element = addClass(document.createElement('div'), 'person');
    console.log(element);