1

I'll be using a textarea as a code editor. I want to get the value of the textarea and it as the CSS for a specified element.

HTML

<textarea class-"editor">
  background: blue;
  border: 1px solid pink;
</textarea>

JS

$('.editor').keyup(function(){
  var editor_contents = $('.editor').val();
  $('#element').css(editor_contents);
});

As you can see, I don't want to choose a specific CSS property to target. I want to apply the value of the textarea in a string on the style property of #element.

2
  • to which style property you want to assign the value to.... you need to target a property to assign the value Commented Dec 15, 2013 at 12:45
  • 2
    give some sample values of editor_contents Commented Dec 15, 2013 at 12:45

2 Answers 2

4

You could use cssText property, this is the way to do it in jQuery:

$('.editor').keyup(function(){
  var editor_contents = $('.editor').val();
  $('#element').css("cssText",editor_contents);
});

That supposes editor_contents is a string containing any CSS rule.

DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I also want to do the reverse. I want to get the CSS of the element and apply it as the value of the textarea. How can I get the CSS of the element as a string?
@Moppy use: $('.editor').val($('#element').attr("style")); jsfiddle.net/2kDzL/1
@A.Wolff: ignoring any other CSS id or class styles though.
4

Don't bother too much with fancy jQuery functions then -- just assign directly to the style attribute of the element:

$('.editor').keyup(function () {
  var editor_contents = $('.editor').val();
  $('#element').attr('style', editor_contents);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.