jQuery – :focus Selector

The jQuery focus selector selects element if it is currently focused. If you are looking for the currently focused element, jQuery(document.activeElement) will retrieve it without having to search the whole DOM tree.

Source Code

<!DOCTYPE html>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
	.focused { background: #1E8CBE; }
<div id="div1">
<h4 tabindex="3">Text 1 (Click here)</h4>
<h4 tabindex="4">Text 2 (Click here)</h4>

jQuery( "#div1" ).delegate( "*", "focus blur", function( event ) {
    var elem = jQuery( this );
    setTimeout(function() {
       elem.toggleClass( "focused", elem.is( ":focus" ) );
    }, 0);


Following example adds the focused class to whatever element has focus.

Text 1 (Click here)

Text 2 (Click here)


No comments yet.

Leave a Reply