1

i am trying to create a very simple html text editor. i have utilised the context menu function to have different format options once a user selects on the highlighted text on screen will have a span tag appended to it.

this is what i have.

function StyleChange(property) {
    var span = document.createElement("span");
    span.style.color = property;

    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

this works fine for changing the colour of the highlighted text. what i would like to do is be able to use this function to change any format of style for the text by passing an extra parameter when the function is called. so when it is called it will say something like. StyleChange('color',red) or StyleChange('background','yellow').

something like

function StyleChange(style,property) {
    var span = document.createElement("span");
    **span.style. + style = property;**

    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

i get an error message with this any ideas?

1
  • What is the error message and what do the ** mean in the second code block? Commented Sep 18, 2014 at 0:25

3 Answers 3

1

Square brackets are used to pass properties, like:

function StyleChange(property, value){
  var span = document.createElement('span');
  span.style[property] = value;
  if(window.getSelection){
    var sel = window.getSelection();
    if(sel.rangeCount){
      var range = sel.getRangeAt(0).cloneRange();
      range.surroundContents(span);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You probably want

span.style += property;

instead.

Another consideration: you don't want to use the name property for your variable, since that's a reserved keyword (as you can see since it's highlighted in blue) and Bad Things™ will happen if you use one.

Comments

0

h2{color:red;}
<h2>hello</h2 

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
You should add explanation.

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.