July 14, 2024

How to dynamically modify elements inside a textarea field?

You have an empty textarea field (or not). Dynamically, with js, you inject code inside this text field. This text contains, among other things, colors or a dominant color for titles, sentences in bold, borders, background colors etc. You would like to change the color codes contained in the code using buttons: here is a solution.

The html part

Start by defining your buttons then your text field:

<div class="button-row">
	<button type="button" class="change product--color-a" id="productA" data-color="#525ca3">product A</button>
	<button type="button" class="change product--color-b" id="productB" data-color="#633bb0">product B</button>
	<button type="button" class="change product--color-c" id="productC" data-color="#31B7BC">product C</button>
	<button type="button" class="change product--color-d" id="productD" data-color="#4EAB8E">product D</button>
	<button type="button" class="change product--color-e" id="productE" data-color="#ff4c00">product E</button>
	<button type="button" class="change product--color-f" id="productF" data-color="#61b09d">product F</button>
	<button type="button" class="change product--color-g" id="productG" data-color="#64A70B">product G</button>
	<button type="button" class="change product--color-h" id="productH" data-color="#00cbf9">product H</button>

	<label for="final-code" aria-hidden="true"></label>
	<textarea id="final-code" name="message"></textarea>


here we define a data-color attribute per button. We define a color set for all “products” (or any other object). Each button corresponds to a product, a brand and represents a color. The dominant color in the textarea field is also in the data-color attribute of a button. This is to be able to return to the original color.

Interact with the text field

Thanks to the js we will proceed as follows:
We insert all our color codes in a “color” variable.

When clicking on the button:

  • we define in a “color” variable the color of the clicked element
  • we define our text field in a “textarea” variable
  • we define the size of our color table


  • for each color contained in the table
  • if a color of the textarea field corresponds to one of the colors of our table
  • we replace this color with the data-color of the clicked button.


 var color =["#64A70B","#525ca3","#633bb0","#ff4c00","#61b09d","#00cbf9","#31B7BC","#4EAB8E"];
 $(".change").click(function() { 
  var colour = $(this).data("color");
  var textarea = $('#final-code');
  var len = color.length;
  for (i=0; i < len; i++) {
   textarea.html(textarea.html().replaceAll(color[i], colour)); 


Leave a Reply

Your email address will not be published. Required fields are marked *