Add custom CSS styles to a webpage using the CSS Style element retrieved from

I am working on an HTML page that has a TextArea and label. My goal is to create CSS classes in the TextArea and apply them to the label:

<textarea id="txtCSS" name="txtCSS" rows="4" cols="50">
    .FC{color:green;}
</textarea>

<label class="FC">Some Text</label>

Can someone guide me on how to achieve this?!

Answer №1

Give this a try

const addCSS = function() {
  const [_,className,style] = document.getElementById("txtStyle").value.match(/\.(\w+){(.*)}/)
  document.querySelector("."+className).style=style;
}
document.getElementById("txtStyle").addEventListener("input",addCSS)
addCSS()
<textarea id="txtStyle" name="txtStyle" rows="4" cols="50">
    .highlight{background-color:yellow;}
</textarea>

<p class="highlight">Highlighted text</p>

Answer №2

Insert the text from the textarea into the style element.

  1. Monitor the input event on the textarea to capture any new content being added.
  2. Attempt to locate the style element using the ID previewStyle. If it exists, append the text. Otherwise, create a new style element and add the content there.

View the live demonstration here

function render(value) {
  let previewStyle = document.getElementById('previewStyle');
  if(!previewStyle) {
    addStyle(value);
  }else {
    previewStyle.innerText = value; 
  }
}

function addStyle(styles) { 
  /* Creating style element */ 
  const css = document.createElement('style'); 
  css.type = 'text/css'; 
  css.id = 'previewStyle'; 

  if (css.styleSheet){
   css.styleSheet.cssText = styles; 
  } else {
   css.appendChild(document.createTextNode(styles)); 
  } 

  /* Appending style to the head tag */ 
  document.getElementsByTagName("head")[0].appendChild(css); 
}

const text = document.getElementById('txtCSS');
text.addEventListener('input', (e) => {
 const content = e.target.value;
 render(content);
});

render(text.value);

Consider using a library to replace the current textarea for enhanced code highlighting, such as:

  • tui-editor
  • ace
  • and more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An algorithm designed to identify matching song lyrics based on a keyword or its fragments

I am currently dealing with a large text file consisting of over 852000 lines, each containing song verses preceded by different numbers like 1., 134-20., or 1231.. The verses may have four or more lines. Additionally, there are variations within the lines ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

Designing with Bootstrap 4 involves incorporating a button that uses the data-toggle attribute set to "collapse" along with an href anchor linked to

I have attempted to link to an ID while also triggering a data-toggle collapse: <a href="#id" data-toggle="collapse" data-target="#collapseTwo" class="btn btn-primary" title="Something cool">Something very cool</a> for linking to this specif ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

Choose the initial full text that corresponds with a portion of the text

I am currently working on a page with multiple <string> tags containing different strings, like 'Is this a String?  Yes'. My goal is to use JQuery to locate the first instance of 'Is this a String?  ' and extract either ...

Struggling to properly render JSON data

Having trouble accessing specific elements in a script that merges local JSON files using AJAX? The script works fine in Chrome Console, but you can't reach certain elements like 'object.country'. Any suggestions on how to tackle this issue? ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Tips for implementing z-index property on table border

I am encountering an issue with an html file that contains a table. The table has one row element with the css property of position: sticky, while the other rows are just example rows with "some text" in each cell. Within column 5 of the regular rows, I h ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Enhancing table field functionality in Backbone.js

In my Backbone application, I am trying to debug the following code outline. window.TableView = Backbone.View.extend({ initialize: function() {... .. .. ... }); }, selectRow: function() { ... ... .. }, render: function() { // ...

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

A guide on triggering a new chart to appear beside the adjacent <div> when a bar is clicked in a highchart

I'm a beginner with Highcharts and I have a requirement for two charts (let's call them Chart A and Chart B). Creating one chart is straightforward. What I need is, upon clicking on a bar in Chart A, a new chart (Chart B) should open next to the ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

What steps should I take to fix an error in my code?

My current objective is to write a program that generates a square with dimensions of 200 pixels by 200 pixels. The square should be colored using specific RGB values: red (red value of 255), green (green value of 255), blue (blue value of 255), and magent ...

Issue with JQuery: object.id is returning as undefined even though it should have a value

While working with JQuery, I encountered a rather peculiar (or possibly foolish) error. The HTML code snippet in question is as follows: <input type="password" name="repeatPassword" id="id_repeatPassword" /> And within my javascript code, I have t ...

Link specifically for the ADFS 2.0 single sign-on application

I've been conducting research on both Google and Stackoverflow but haven't been able to find a solution to my problem. Within my ADFS portal, there are 5 different services that can be selected. I'm trying to determine how I can generate a ...

Can anyone provide guidance on how to calculate the total sum of a JavaScript array within an asynchronous function?

Currently, I am working with Angularjs Protractor for end-to-end testing and faced an issue while trying to calculate the sum of values in a column. Although I am able to print out each value within the loop successfully, I am struggling to figure out ho ...

Troubleshooting problems with footer size in wkhtmltopdf

I am facing an issue while trying to convert an HTML file to a PDF format. Specifically, when attempting to include a footer, the size rendered in the PDF does not match the one specified in the CSS. The designated size for the footer should be exactly 15 ...

Encountered a MySQL error while attempting to insert an image into the database

I have a task to work on a website where users can upload product images that will be stored in a MySQL database. The code for my HTML form is: <FORM action="testimage1.php" ENCTYPE="multipart/form-data" method="post"> <div st ...

Changing my PHP contact form from method GET to POST is causing it to malfunction

Feel free to check out my contact form on benlevywebdesign.com, located at the bottom of the page. <form id="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="text/plain" method="get"> <fieldset> ...