skip to Main Content

I’m trying to use the css attribute selector in document.querySelector() to find the input which a certain value. The input has a default value which was set using the input value attribute when the page was built. Once the user has changed the value, if the value attribute is set, the selector still uses the original default value specified on the element.

Here is an example which outlines the problem:

document.querySelector("#button").addEventListener("click",function(){
    var element = document.querySelector("input[value='foo']")
  if(element){
    alert("element found")
  }else{
    alert("element not found")
  }
})
<div>
  <label>
    Label:<input value="foo">
  </label>
  <button id="button">
    Will find element, even if value is changed from foo
  </button>
</div>

I would expect the element to stop being found once the value is changed from ‘foo’ but it continues to find it even once the value is changed.

Is there a way to have this work with the actual value in the input, rather than the value set in the value property on the input?

2

Answers


  1. An <input>‘s value can be read in JavaScript via the HTMLInputElement‘s value property. You could use this in conjunction with .querySelectorAll('input') and then filter the results to see if there are any matches for the value:

    document.querySelector("#button").addEventListener("click",function(){
      var element = Array.from(document.querySelectorAll("input"))
        .filter(({ value }) => value === 'foo')?.[0];
      if(element){
        alert("element found")
      }else{
        alert("element not found")
      }
    })
    <div>
      <label>
        Label:<input value="foo">
      </label>
      <button id="button">
        Will find element, even if value is changed from foo
      </button>
    </div>
    Login or Signup to reply.
  2. No.

    CSS has no selector that keys off arbitrary object properties or the value attribute in particular.

    The closest you could come would be to set a pattern attribute on the input and then key off the :valid or :invalid psuedo-classes. Obviously, setting pattern would have significant other effects on form submission.

    You would probably be better finding all input elements (or all input elements that are members of a particular class), dropping them into an array and then filtering that array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search