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
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. Theelement
variable itself was never changed, but.classList.add()
changed some internal property ofelement
.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 theelement
variable has the valueundefined
. 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:The code snippet:
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.