Home > OS >  Style html elements dynamically based on id
Style html elements dynamically based on id

Time:10-06

I want to color different elements based on their own ids. If their id is in a list of id's given by me, make it a color, if not, make it another color.

In the example below are 4 div's, each a different color. How can I color each div depending on his id without defining css rules for each of them?

const Main = () => {
return (
    <React.Fragment>
    <div id='1' style={{background: 'red'}}>1</div>
    <div id='2' style={{background: 'blue'}}>2</div>
    <div id='3' style={{background: 'green'}}>3</div>
    <div id='4' style={{background: 'cyan'}}>4</div>
  </React.Fragment>
    )
}

https://jsfiddle.net/9debt3cL/19/

If the question is not very clear, let me know.

UPDATE: Context: I have an svg blueprint divided into multiple parts, each with a unique number. I have to fetch some data containing some parts of the blueprint numbers and depending on those numbers to fill the blueprint paths.

CodePudding user response:

Not completely sure if it would work but you could always try, look into a switch case using javascript. Set the expression and have different cases depending on the value etc. Can be Id in this example and have a different outcome depending on the case.

CodePudding user response:

I think Wanz has the right approach, you can create css classes with the desired attributes. Then add this class to the dom element if it corresponds to the switch case. Like so:

  var element = document.getElementById("myDIV");
  switch (expr) {
  case 'id1':
  element.classList.add("styleId1");
  break;
  case 'id2':
  element.classList.add("styleId2");

  case 'id3':
  element.classList.add("styleId3");

  break;
  default:
    console.log(`no matching id`);
}

CodePudding user response:

You could so something like this:

const Main = () => {
  const coloredIds = ['1', '4'];

  const getBackgroundColor = (id) => {
     return coloredIds.includes(id) ? 'cyan' : 'red';
  }

  return (
    <React.Fragment>
      <div id='1' style={{background: getBackgroundColor('1')}}>1</div>
      <div id='2' style={{background: getBackgroundColor('2')}}>2</div>
      <div id='3' style={{background: getBackgroundColor('3')}}>3</div>
      <div id='4' style={{background: getBackgroundColor('4')}}>4</div>
    </React.Fragment>
  );
}

or if you have multiple colors

const getBackgroundColor = (id) => {
  switch (id) {
    case '1':
      return 'red';
    case '2':
      return 'blue;
    case '3':
      return 'green';
    case '4':
    default:
      return 'cyan';
  }
}

CodePudding user response:

Here's a updated jsfiddle of your attempt: https://jsfiddle.net/fyLab6zr/21/

Not sure it's exactly what you wanted, but the colors is specified in the css, so the list of ids that should give certain colors, as well as a default color for all those that do not match:

.background {
  background: red;
}

.background-1, .background-2 {
  background: blue;
}

.background-3, .background-4 {
  background: green;
}

And then you have a list of ids that you can iterate over to populate the specific ids rows. Passing in the id in background-${id} to set the className equal to the corresponding id. It will then be styled if it exist, or use the fallback 'background' class

const Main = () => {
const ids= [1,1,3,2,1,3,4,5, 6, 1]
return (
    <React.Fragment>
    {ids.map((id) => {
        return <div id={id} className={`background background-${id}`}>{id}</div>  
    })}
  </React.Fragment>
    )
}

ReactDOM.render(<Main />, document.querySelector("#app"))

Edit:

This approach creates your predefined lists of ids, in this example two lists, leading to two different colors. It still defaults back to background if none match. The getColor function gives the correct className based on id. And you can also predefine as many elemnts as you want.

const color1 = [1,2]
const color2 = [3,4]

const getColor = (id) => {
   return color1.includes(id) ? 1 : color2.includes(id) ? 2 : -1
}

return (
    <React.Fragment>
        <div id="1" className={`background background-${getColor(1)}`}>1</div>
        <div id="2" className={`background background-${getColor(2)}`}>2</div> 
        <div id="3" className={`background background-${getColor(3)}`}>3</div>   
        <div id="4" className={`background background-${getColor(4)}`}>4</div> 
        <div id="5" className={`background background-${getColor(5)}`}>5</div> 
    </React.Fragment>
    )
}

ReactDOM.render(<Main />, document.querySelector("#app"))
  • Related