Add color to javascript text

Asked

Viewed 2,289 times

0

Hello, I have a problem, I need to add a color to a text that is added inside a textarea through a button.

I tried to use x.style.color="red'"... but it didn’t work, if someone has a solution please introduce me.

Follows the code:

<body>
<textarea name="texto" id="texto">
</textarea>

<button class="button button2" type="button1">Texto</button>

<script>
var textarea = document.querySelector('textarea');
var button1 = document.querySelector('button');
var assinatura1 = 'TEXTO COLORIDO'
button1.addEventListener('click', function() {
    textarea.value += assinatura1;
});
</script>
</body>
  • What would be x in x.style.color="red'"?

  • "X" would be the variable, since the text (COLORED TEXT) is passed to the textarea via the signing variable1.

  • You want to change only the text "COLORFUL TEXT" and leave others without coloring?

  • Yes, if possible, since the text "COLORED TEXT" is inserted in the textarea without deleting what was already written.

  • I get it, but there’s already question addressing it. Take a look.

1 answer

0

Hello by javascript you can do this way:

// Change the background color:

document.getElementById('texto').style.backgroundColor = 'blue'; // ou a cor que quiser

// Muda a cor do texto:
document.getElementById('texto').style.color = 'black';
  • Hi Renato, I had already tried this second option that you suggested. However I could not, I forgot to inform that the text that should gain color is the "COLORED TEXT", and that it is assigned to a variable, in this case the variable "signature1", and the suggested way it did not work... Would have another way?

  • you can assign a color to the whole textarea, not for a text only.

  • To do this you need an element that allows you to insert content html, as a div or span

  • Hello @Sulivansantos, as Ricardo said, within the same element there is no way, you need to create a div and separate the elements and then yes you can do the way I gave you. I hope I helped. Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.