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
An
<input>
‘s value can be read in JavaScript via theHTMLInputElement
‘svalue
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: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 theinput
and then key off the:valid
or:invalid
psuedo-classes. Obviously, settingpattern
would have significant other effects on form submission.You would probably be better finding all
input
elements (or allinput
elements that are members of a particular class), dropping them into an array and then filtering that array.