Error when trying to add class dynamically with classList.add() and classname

Asked

Viewed 41 times

1

If I create an element and already add a class to it like this:

let paragrafo = document.createElement('p').classList.add('text')

Then try to add a child element to it like this:

text = document.createTextNode('texto')<br>
paragrafo.appendChild(text)

Keeps making the mistake of: Cannot read property 'appendChild' of undefined.

If I change and try to add with classname of error : paragrafo.appendChild is not a function

But if I take the classList/classname from above, and don’t add a class works normal, however I need to add this class. Why I have this result and how can I create the element and then add the class using pure Javascript only?

2 answers

3

First you create the element:

let paragrafo = document.createElement('p');

Then you add the class:

paragrafo.classList.add('text');

You can’t do both at once.


Another way would be:

let paragrafo = document.createElement('p');
paragrafo.className = 'text';

The .classList.add adds a class, even if there are others (or none). Already the .className sets a unique class to the element (rewrites the attribute class).

2

What’s going on is that you’re coding pure javascript as if you’ve been using jQuery.

When you put:

console.log( 'createElement' , document.createElement('p') );
    /// retorna um HTMLElement  <p>

console.log( 'classList' , document.createElement('p').classList );
    /// retorna um DOMTokenList  []

console.log( 'classList.add' , document.createElement('p').classList.add("minhaclasse") );
    /// retorna undefined

I mean, your let paragrafo is receiving Undefined and not a Htmlelement.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.