Home > Back-end >  I want to get the ID of the first input with a green color within inputs array and then change the c
I want to get the ID of the first input with a green color within inputs array and then change the c

Time:12-25

I want to get input ID here and use it to change input color to be grey. Then repeat the process for other inputs with green color

var getGreenColor = document.getElementsByClassName("my_inputs")[0].color;

if (getGreenColor == "green") {
  console.log("green")
}
else console.log(getGreenColor)
<input type="text" style="color: green;" id="1"  value="stuff">
<input type="text" style="color: green;" id="2"  value="stuff">
<input type="text" style="color: green;" id="3"  value="stuff">
<input type="text" style="color: green;" id="4"  value="stuff">

CodePudding user response:

Just use

var elements = document.getElementsByClassName('my_inputs');
for (let a=0; a < elements.length; a  ) {
    if (elements[a].color == 'green') {
        elements[a].color = 'grey';
    }
}

This will loop through the elements and if it is green, turn it to grey.

CodePudding user response:

You could also you css attribute selector if your color is always set inline:

input[style="color: green;"]:first-of-type {
  background: red;
}
<input type="text" style="color: green;" id="1"  value="stuff">
<input type="text" style="color: green;" id="2"  value="stuff">
<input type="text" style="color: green;" id="3"  value="stuff">
<input type="text" style="color: green;" id="4"  value="stuff">

CodePudding user response:

You need the style.color or getComputedStyle

The style.color is undefined if not inline

const styles = window.getComputedStyle(document.getElementsByClassName("my_inputs")[0])

const color = document.getElementsByClassName("my_inputs")[0].style.color;
if (color === "green" || styles["color"] === "rgb(0, 128, 0)") {
  console.log("green")
}
else console.log(styles["color"])
<input type="text" style="color: green;" id="1"  value="stuff">
<input type="text" style="color: green;" id="2"  value="stuff">
<input type="text" style="color: green;" id="3"  value="stuff">
<input type="text" style="color: green;" id="4"  value="stuff">

  • Related