Home > other >  How do i change the color of an appended string?
How do i change the color of an appended string?

Time:02-19

I've a div

<div ></div>

Inside this div i want to append some text using a JavaScript event listener

const calculatorDisplay = document.querySelector(".display-container")
function appendNumber(number) {
calculatorDisplay.append(number)
}
// number event listener
one.addEventListener("click", () => {
calculatorDisplay.append(1)
})

it work perfecly, but the problem here is that the background color of the display-container div is black, and the default color for string is black, so, how do i change the color of an appended string? i've already tried using the style tag, but that does not work, i've tried using fontcolor() too, but that too doesn't worked. I've noticed that the appended string have an id of #text, but i cannout use it if i try.

CodePudding user response:

Define css class

<style>
.colored-text { 
   color: red;
}
</style>

And then create span element with colored-text class and append it

// number event listener
one.addEventListener("click", () => {
  const newSpan = document.createElement('span');
  newSpan.classList.add('colored-text');
  newSpan.textContent = 1;
  calculatorDisplay.append(newSpan);
})

BTW. why are you defining appendNumber function and not using it?

CodePudding user response:

There are several ways to achieve this.

javascript

const calculatorDisplay = document.querySelector(".display-container")

// changing the color to red
calculatroDisplay.style.color = 'red';

// it accepts also Hex colors
calculatorDisplay.style.color = '#FF5733'

// OR rgb 
calculatorDisplay.style.color = 'rgb(255,0,0)

CSS

It is also possible to append a classname to your div. Like this you could make the code probably more reusable and may apply more styles than just colors in a simple manner. (There are multiple ways to include CSS in your html, google it^^ )

// within in the <head> tag in the html add a <style> tag. 
<html>
<head>
   <style>
       .red-color {
            color: red
        }
   </style>
</head>
<body>
<!-- .....  --->
</body>
</html>

In the code you can now add a classname using element.classList.add() OR element.classList.remove() to remove classes!

function setRedColor(el) {
    el.classList.add('red-color')
}

function removeRedColor(el) {
   el.classList.remove('red-color')
}

const calculatorDisplay = document.querySelector(".display-container")
setRedColor(calculatorDisplay)
// ...
removeRedColor(calculatorDisplay)

Note that the element.classList API generally does not allow classnames with a whitespace in it. So if you have mutliple classes you have to apply them one by one or you'll run into an error.

Feel free to leave a comment

  • Related