I want to change the color of tr element when user select a text box inside it. The focus pseudo-class is not working with it. Can this be achieved without JavaScript ?
html:
<table>
<tr>
<td>Name</td><td><input type="text" name="name"></td>
</tr>
</table>
CSS:
tr:focus
{
background:yellow;
}
Update1:
Looks like there is no CSS only method. What is the easiest way to do this using JavaScript ?
What about using :focus-within...
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
</table>
CSS:
tr:focus-within {
background:yellow;
}
Fiddle
What helped me. As the chosen answer did not work for me.
No. There's no subject selector in CSS3, there will be one in CSS4 though.
EDIT:
A pure JavaScript solution could be
var i;
var inputs = document.querySelectorAll("tr > td > input");
for(i = 0; i < inputs.length; ++i){
inputs[i].addEventListener('focus',function(e){
this.parentNode.parentNode.className += ' highlight';
});
inputs[i].addEventListener('blur',function(e){
this.parentNode.parentNode.className = this.parentNode.parentNode.className.replace(/\s*highlight\s*/ig,' ');
});
}
However, this won't work in IE≤7, as versons prior 8 don't know document.querySelectorAll
(demonstration). If you want a care-free cross-browser solution you could use jQuery and the following code (demonstration):
$("tr > td > input").focus(function(e){
$(this).parent().parent().addClass('highlight');
}).blur(function(e){
$(this).parent().parent().removeClass('highlight');
});
Don't forget to add a class tr.highlight
to your CSS. Keep in mind that jQuery will drop support of old browsers in future releases (see Browser Support), so you'll have to use jQuery 1.x for IE ≤8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With