Hello, I am new to this and still learning the new stuff :)
I have a question about mine javascript and i hope this is the right area to get a answer :)
So i made a code that every 2e of 3e word change from color(its a bit random). I used 'getElementById' but i know so far mine knowledge goes that it only works for 1 id. And i want to use the code on more places with diffrent "id's" but don't want to duplicate mine code.
Could some on explain to me what to do? Or is there documentation i could read with some explanation how to make maybe a function with the code? I hope some on could explain how to clean this up ;)
Here is mine code:
var paragrapgh = document.getElementById("ads_colordtitel");
var words = paragrapgh.innerText.split(" ");
var colors = ["#0B88EE", "#FFFFFF"];
var spans = [];
for(var x = 0; x < words.length; x++){
var color = colors[Math.floor(Math.random()*colors.length)]
var span = "" + words[x] + ""
spans.push(span);
}
paragrapgh.innerHTML = spans.join(" ");
Top comments (2)
You could extact your logic into a function which accepts a parameter with the id you want to write your spans in.
I didn't really change any of your color-logic. I only replaced the for-lop with a forof-loop. I also changed your
var
toconst
. Last change I made was to use template literals to construct the<span></span>
.The function could look like this:
Notice I changed it to
document.querySelector
. This will also allow you to use classes as the selector too, not just IDs.Full example:
As a Codesandbox.
Awesome Alexander, thank you verry much for the explanation! This helped a lot!