Skip to content
Advertisement

Save ID in variable and add style to it

I want to highlight randomly a word which is inside a <p> tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can’t add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two". Like:

<p id="JShighlight"> <span id="one">Lorem </span><span id="two">Ipsum </span><span id="three">Dolores</span></p>

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

let childNodeArray = document.getElementById('JShighlight').children;

Then I randomly chose an index:

  let i = Math.floor(Math.random() * childNodeArray.length);

The variable name saves the randomly chosen ID.

let name = childNodeArray[i].id;

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time. I tried:

name.classList.add("blinking");

(.blinking is the css-class:

.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}

)

But it does not work. What “works” is:

document.getElementById(name).style.color = "red";

Why can I pass a variable as an argument in the latter case and not in the former case? How can I append a css class to an variable ID?

Advertisement

Answer

Instead of

let name = childNodeArray[i].id;

try

let name = childNodeArray[i];

Hope your issue will be resolved;

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement