Change the color <tr> when the element inside is in focus
I want to change the color of the tr element when the user selects a text box inside it. Focus pseudo-class does not work with it. Can this be done without JavaScript?
HTML:
<table> <tr> <td>Name</td><td><input type="text" name="name"></td> </tr> </table> CSS
tr:focus { background:yellow; } Update1:
It looks like there is no CSS only method. What is the easiest way to do this using JavaScript?
Not. There is no thematic selector in CSS3, but there will be CSS4 .
EDIT
A clean JavaScript solution might 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 will not work in IE & le; 7 since versons before 8 do not know document.querySelectorAll ( demo ). If you want a carefree cross-browser solution, you can use jQuery and the following code ( demo ):
$("tr > td > input").focus(function(e){ $(this).parent().parent().addClass('highlight'); }).blur(function(e){ $(this).parent().parent().removeClass('highlight'); }); Remember to add the tr.highlight class to your CSS. Keep in mind that jQuery will no longer support older browsers in future releases (see Browser Support ), so you will have to use jQuery 1.x for IE & le; 8.
No, you cannot without JavaScript.
It is technically possible to make the tr element oriented in fairly new browsers using the tabindex attribute on it, for example. <tr tabindex="1"> .
However, the focusing method is browser-dependent, and the oriented rows of the table can be a usability nightmare. For example, in both IE and Firefox, the string focuses on when the TAB key is used appropriately, but the focused string does not accept input. To use this field, you will need to press TAB again to go to the input field. In Firefox, but not in IE, this line can also be focused by clicking, but not clicking on the input field (since this will focus on this field). If you use label markup as recommended for ease of use and accessibility, e.g.
<table> <tr tabindex="1"> <td><label for="name">Name</label></td> <td><input type="text" name="name" id="name"></td> </tr> </table> ... then clicking on the label focuses on the input field (one of the reasons for using label layout!), and not on the line element.
How about use: focus inside ...
<table> <tr> <td>Name</td> <td><input type="text" name="name"></td> </tr> </table> CSS:
tr:focus-within { background:yellow; } What helped me. Since the selected answer did not work for me.