Applying CSS rules from an array to elements by looping through

I'm looking for a way to allow users to input CSS styles and have those styles applied to the last selected element, which is determined by the "rangeselector" variable. Currently, the code selects the correct element, but only the first CSS rule is being applied.

For example, if a user inputs "background: blue; color:red;", only the background property gets applied.

The function successfully iterates through the array.

function customCss(){
  css = $("input.css").val();
  if(css.length < 10){
        alert("Please enter 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 have any insights into the issue, or a better approach to accomplish the same goal, I would appreciate your suggestions.

Thank you

Answer №1

When utilizing the Array.forEach() method, you automatically have access to the index and a reference to the Array itself. This eliminates the need for using a separate counter variable.

    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;
    });

Answer №2

Before setting the elements, have you considered removing any extra spaces? It seems like the issue might be caused by trying to set "color " instead of just "color".

function applyCustomCss(){
  customCss = $("input.css").val();
  
  if(customCss.length < 10){
    alert("Please insert valid CSS");
  } else {
    cssRules = customCss.split(";");
    counter = 0;
    
    cssRules.forEach(function(){
      var ruleSplit = cssRules[counter].split(":");
      targetElement = $("[content_child=" + rangeselector + "]");
      targetElement.css(ruleSplit[0].trim() , ruleSplit[1].trim());
      counter = counter + 1;
    });
  }
}

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

Applying a CSS border to a div that perfectly encloses a span, adjusting to the

My goal is to create a nested structure where a div contains a span element like this: ---------- |Sentence| ---------- ----------------- |It's a looooong| |sentence | ----------------- While it works well for short sentences, long ones end u ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...

Encountering a problem with React router

Hello, I'm currently facing some issues with setting up routes in my project. Below is the code snippet from my route.js file: import React, { Component } from 'react'; import Home from './Home'; import Add from './Add' ...

How to generate a dropdown menu using a deeply nested JSON array

I'm looking to create a series of drop-down lists based on the JSON array provided below. There will be five drop-down lists, and when I select an option in one list, the other four should populate accordingly. For example, if I choose "Hindi" in the ...

Is there a way to switch out the navigation icons on the react-material-ui datepicker?

Can the navigation icons on the react-material-ui datepicker be customized? I've attempted various solutions without any success. <button class="MuiButtonBase-root MuiIconButton-root MuiPickersCalendarHeader-iconButton" tabindex="0&q ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

When running through a loop, the JSON array data containing the merged arrays is not being shown as expected

After combining the two PHP arrays $pricelist and $product and encoding them with JSON, the resulting JSON array is as follows: The PHP arrays look like this: Array ( [0] => Array ( [PriceList] => Array ( ...

When using jQuery's $.when in a loop, it does not pause for each call to finish before moving on to the next iteration of the loop

Using $.when to make AJAX calls within a loop is causing unexpected results: for ( var i = 0; i < 4; i++ ){ $.when(get_total_price("var1","var2")).then(function (v) { console.log("i= "+i); }); } The expected output should be: i= 1 i= ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Issue with MUI Autocomplete not showing selected name on initial option selection

I encountered a strange issue with the Autocomplete component from Material UI. Here is the code snippet in question: const [isContactListInitialised, setContactListInitialised] = useState(false); const toggleContactListInitialized = () => { setContactL ...

Utilize vue.js to cache and stream videos

I'm new to the world of vue.js and I'm facing a certain dilemma. I implemented a caching system using resource-loader that preloads my images and videos and stores the data in an array. Everything is functioning correctly, but now I'm unsur ...

Sorry, but we are experiencing difficulties processing your request at the moment. HTTP ERROR 500: We are unable to locate the

My code seems to be functioning correctly when connecting to the database, but I'm encountering an error. Here is the code snippet: <?php include 'header.php'; ?> <!DOCTYPE html> <html> <head> <t ...

Error handling form inputs dynamically using AJAX based on user input

Struggling to find any valuable answers regarding this topic: It involves a simple ajax form process handler: $(document).ready(function(){ }); function functionToUpdate(id) { var data = $('form').serialize(); $('form').unbind ...

What is the process of compiling a Vuejs single file component?

Seeking assistance with Vuejs 2 (webpack-simple template) - I am looking for a way to compile my template before rendering it. Below is the code snippet in question: App.vue <template> <div id="app"> <h1>{{ msg }}</h1> ...

I am puzzled by the fact that the center cell of my table is longer than the surrounding cells

I'm currently working on a project that involves creating a webpage. I have a table, and when I execute the code, I notice that the center cell appears longer than the rest of the cells. table,td,tr{border: 1px solid red; } <!document html> ...

Having various ng-apps within a single parent app

Exploring angularjs for the first time and experimenting with multiple ng-apps on a single page. For example, having app2 inside app1 and app1 within rootApp. controller1 includes an $http service that retrieves id and name values and assigns them to $roo ...

Angular is unable to eliminate the focus outline from a custom checkbox created with Boostrap

Have you noticed that Angular doesn't blur out the clicked element for some strange reason? Well, I came up with a little 'fix' for it: *:focus { outline: none !important; } It's not a perfect solution because ideally every element sh ...

What is the best way to ensure that the content container's max-width for a split tier is the same as the width of a full-width tier?

My goal is to create a split tier on a webpage with a 60/40 layout. The size of this tier should be calculated based on the maximum width of the container above it. Using JavaScript and jQuery, I managed to derive the max-width value of the full-width-tier ...