0

I want users to be able to input CSS input, and have that CSS applied to the last selected element(selected by the "rangeselector" variable). The code selects the right element, but only the first CSS-rule is applied.

ex: "background: blue; color:red;" only applies the background.

The function runs through the array correctly.

function customCss(){
  css = $("input.css").val();
  if(css.length < 10){
        alert("Insert valid CSS");
  }else{

        cssArray = css.split(";");
        counter = 0;
        cssArray.forEach(function(){
              var ruleSplit = cssArray[counter].split(":");
              target = $("[content_child=" + rangeselector + "]");
              target.css(ruleSplit[0] , ruleSplit[1]);
              counter = counter + 1;
        });
  }
}

If you know the problem, or have a better way of achieving the same goal, i would gladly hear you suggestions.

Thanks

3
  • In what format the user input the CSS? Commented Feb 19, 2015 at 21:16
  • How you would write it in a document Commented Feb 19, 2015 at 21:22
  • Where is rangeselector defined? Commented Feb 19, 2015 at 21:23

2 Answers 2

1

By using Array.forEach() you already have the index and the reference to Array. You don't need use a counter

    cssArray = css.split(";");
    // counter = 0;
    cssArray.forEach(function(obj, key, array){
          var ruleSplit = obj.split(":");
          target = $("[content_child=" + rangeselector + "]");
          target.css(ruleSplit[0] , ruleSplit[1]);
          // counter = counter + 1;
    });
Sign up to request clarification or add additional context in comments.

Comments

0

have you tried stripping the elements before you set them? What's probably happening is that it's trying to set something like "color " instead of "color"

function customCss(){
  css = $("input.css").val();
  if(css.length < 10){
        alert("Insert valid CSS");
  }else{

        cssArray = css.split(";");
        counter = 0;
        cssArray.forEach(function(){
              var ruleSplit = cssArray[counter].split(":");
              target = $("[content_child=" + rangeselector + "]");
              target.css(ruleSplit[0].trim() , ruleSplit[1].trim());
              counter = counter + 1;
        });
  }
}

1 Comment

I'd also consider refactoring the code like nanndoj suggested, you have no need for a counter.

Your Answer

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