Search code examples
javascriptcsscss-animationsappendchild

Creating a <p> element and changing style in same function


Hope you're all having a good day.

I'm using "createElement" and "appendChild" to make a paragraph inside of a div.

The code looks like this (sorry for the crude work):

var para = document.createElement("p");
para.id = "cursorText";
var node = document.createTextNode(rand);
para.appendChild(node);
var element = document.getElementById("cursorPos");
element.appendChild(para);

This creates the paragraph and puts a random word inside of it, and appends it to the div "cursorPos".

It creates an element like the following:

<p id="cursorText">Hello StackOverflow</p>

The text inside the id para is changed with every click of a button (to a random word from an array) and the goal is to have it fade out after every click.

I am trying to do this with the following code:

var elem = document.getElementById("cursorText");
elem.style.transition = "opacity 2.0s linear 1s";
elem.style.opacity = "0";

but it keeps telling me "Uncaught TypeError: Cannot read property 'style' of null" @ Line 40 AKA the line that starts elem.style.transition...

please bear in mind the following: The 2 attributes (creating the text node and the animation) have to be in the same function. I've already tried it in a separate function and it did not work.

thanks for reading this cryptic mess, any help is highly appreciated :)


Solution

  • You put the ID as "cursorText", instead of "para".

    Also, I would personally recommend you create a CSS class, and set the class attribute on the new object to match that CSS class with all of the changes you want to make to the newly created paragraph.