Is it possible to use an input value attribute as a CSS selector?

后端 未结 9 2334
[愿得一人]
[愿得一人] 2020-11-27 17:07

Is it possible to use a CSS selector to target an input that has a specific value?

Example: How can I target the input below based on the value=\"United States

9条回答
  •  甜味超标
    2020-11-27 17:28

    Following the currently top voted answer, I've found using a dataset / data attribute works well.

    //Javascript
    
    const input1 = document.querySelector("#input1");
    input1.value = "0.00";
    input1.dataset.value = input1.value;
    //dataset.value will set "data-value" on the input1 HTML element
    //and will be used by CSS targetting the dataset attribute
    
    document.querySelectorAll("input").forEach((input) => {
      input.addEventListener("input", function() {
        this.dataset.value = this.value;
        console.log(this);
      })
    })
    /*CSS*/
    
    input[data-value="0.00"] {
      color: red;
    }
    
    
    

    Input1 is programmatically set by JavaScript:


    Try typing 0.00 inside input2:

提交回复
热议问题