Lewis H
Lewis H

Reputation: 59

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 :)

Upvotes: 0

Views: 127

Answers (2)

constnt
constnt

Reputation: 16

when you made your variable elem, you told to get by an id you never initialized. If you look at your para class you'll notice your outputted id is id="cursorText" Though when you tried to stylize, you told it to grab id="para". Therefore you you received null.... quick fix would be to just change you id query function. i.e.

var elem = document.getElementById("cursorText");

Upvotes: 0

Aetricity
Aetricity

Reputation: 149

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.

Upvotes: 2

Related Questions