Customizing the appearance of an HTML element using user-input text styling

On my webpage, there are two text areas and a division. One of the text areas is meant for users to input HTML code, while the other is for CSS code. Whenever a button is clicked, a JavaScript function will be triggered to display the combined HTML and CSS within the division.

function handleLaunch() {
  var div = document.getElementById('pane');
  var html = document.getElementById('h');

  var css = document.getElementById('c');

  div.innerHTML = html.value;
  // In this part, the css value needs to be set differently: div.style = css.value;
}
<body>
  <textarea id="c" placeholder="Insert CSS code here..." rows="10" cols="50"></textarea>
  <div id="pane">

  </div>
  <br>
  <textarea id="h" placeholder="Add Html code here..." rows="10" cols="50"></textarea>
  <br>
  <button type="button" onclick="handleLaunch()">Launch</button>

To determine how to implement the CSS as text, one must consider...

UPDATE: It should be noted that I would like to include something like ".classExample{text-align:center}" in the CSS text area and apply it on the content.

Answer №1

Indeed, the solution provided by @adeneo is effective. You can test it out with this code snippet. Simply input color: red; as CSS and any desired text as HTML...

function updatePage() {
  var container = document.getElementById('pane');
  var contentHtml = document.getElementById('htmlContent');

  var cssStyle = document.getElementById('cssStyle');

  container.innerHTML = htmlContent.value;
  container.style.cssText = cssStyle.value;
}
<body>
  <textarea id="cssStyle" placeholder="Insert CSS style here..." rows="10" cols="50"></textarea>
  <div id="pane">

  </div>
  <br>
  <textarea id="htmlConent" placeholder="Add HTML content here..." rows="10" cols="50"></textarea>
  <br>
  <button type="button" onclick="updatePage()">Update Page</button>

Answer №2

If you are setting css properties along with selectors, for instance your css text is as follows:

div{
    background:red;
}
.someClass{
    font-size:12px;
}

and your html appears like this:

<div>DIV content</div>
<span class="someClass"> Content in someClass</span>

To insert the html, use div.innerHTML = html.value;

However, to apply the css to your page, you must follow these steps:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = document.getElementById('c').value;
document.getElementsByTagName('head')[0].appendChild(style)

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

Exploring the process of sending JSON responses through Express

I recently started working with node/express. My express app has a single post route ('/'), which is designed to retrieve information about GitHub users based on their usernames. For instance, when I make a post request like this { "develop ...

In Chrome browser, the orientation of the options in the datalist remains consistent

Is there a way to change the direction of the datalist's options to RTL? While I'm able to change the direction of the input element, the same doesn't apply to the options of the datalist. I've attempted setting the dir attribute to r ...

I am unable to invoke this function: TypeError: this.fetchData is not a function

Whenever I try to execute this.fetchData();, I encounter the error "TypeError: this.fetchData is not a function". Initially, I suspected that the context of 'this' was lost so I attempted using bind and arrow functions without success. How can I ...

jquery form submission issue unresolved

I am currently utilizing jQuery version 1.10.1 and here is a snippet of my HTML code: <li> <a href='' id='logout'>Log Out</a></li> <form id='logout_form' method='post'> <i ...

What are the reasons for avoiding placing CSS code directly within HTML?

Situation: My website is dynamically served, with all CSS and javascript directly embedded into the HTML document to optimize speed. Advantages: Reduces web requests Fewer files downloaded Speeds up webpage loading time Disadvantages: Potential cachin ...

Is there a way for me to obtain a selection of 20 random items from this JSON data

When working with my JSON data using Myjson.slice(1, 20), I encountered a situation where I needed to extract only 20 items from a dataset that had a length of 2624. In the code snippet provided, I attempted to use the slice method but struggled to differe ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Attempting to enhance the modularity and readability of my code

Looking for assistance to enhance the modularity and readability of this lengthy code. Any tips on how to simplify it and improve clarity would be greatly appreciated! I'm currently working on a street fighter game, and here's what I have so far ...

The nuSelectable plugin enhances the functionality of jQuery

I am currently experimenting with the jQuery nuSelectable plugin in order to enable users to select multiple items simultaneously. Unfortunately, I am encountering difficulties in making the selection work as intended. You can find the plugin here. After ...

Using this.setState in ReactJS removes filters

Hey everyone, I've been struggling with a technical issue for the past few days and would really appreciate any hints or solutions. The problem lies in creating a table using the material-table library. Specifically, I need to extract the docID and do ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

"An error occurs when trying to trigger a .click() event within a list element

There is a list that can contain either plain text or a link. If there is a link present, the entire list element should be clickable. When attempting to execute the following code: if ($('.link').length) { $('li[data-contains-link]' ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

Tips for implementing a CSS Flexbox layout with varying div heights

I am working on a page that features five unique panels, each with its own distinct height and width. I have been considering implementing CSS Flexbox to ensure these panels stack properly as the page becomes responsive. However, one major issue I've ...

What is the best way to seamlessly integrate an image icon into a sentence, so it appears as a natural part of the text

I'm struggling to insert an (i) information icon before the phrase "Learn more" in the sentence: "Click on the 'Learn more' buttons for additional information." The icon keeps overlapping with the words "Learn more." Could someone provide s ...

Dynamically update a form with steps using JQuery-steps and send all objects to the controller

In the context of a form, it is possible to dynamically add between 1 to n records before passing it to the controller with data. The following represents the ViewModel for the form: public class AddFieldDataViewModel { public int SampleID { get; se ...

"Customizing the Material-ui TextField DOM Element: A Step-by-Step

After trying the code below, I was expecting to see a yellowish "Hi," but instead received [object Object]. Is there a way to correct this issue? Possibly utilizing InputProps would help, but I haven't been able to locate a comprehensive tutorial on ...

Encountered issues loading JavaScript and received a pyppeteer error while trying to access a website through requests

I am facing a challenge when trying to scrape a webpage post login using BeautifulSoup and requests. Initially, I encountered a roadblock where the page requested JavaScript to be enabled to continue using the application. To work around this issue, I de ...

Items are overflowing the flex container, exceeding its boundaries

I've experimented with the width property, flex, flex-basis, and flex-shrink, but so far nothing seems to be working. I can't seem to pinpoint where the mistake lies in the code. I wanted to include the code snippet here, but it's throwing ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...