skip to Main Content

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');

2

Answers


  1. 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);
    Login or Signup to reply.
  2. The code snippet:

    document.createElement('div').classList.add('person')
    

    is not considered valid because the classList.add() method does not return the current element with the added class. Instead, it returns undefined.

    The correct approach is to first create the object using document.createElement('div'), and then add the class to the element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search