Getting the element that has the focus via JavaScript

This is one of those things that you only need on very specific occasions. I needed to get the element that has the focus on a page. Went to Google and found the answer somewhere deep into a forumthread. So for future reference here goes:
Internet Explorer supports the document.activeElement property which gives exactly what I was looking for: the element that has the focus. Because you always have to be careful about javascript properties that are described on a MSDN page, they could be Internet Explorer only, I decided to write a little test to see if it works in the major browsers. I tested this in the following browsers (and corresponding platforms):

  • Internet Explorer 6 – Windows
  • Internet Explorer 7 – Windows
  • Internet Explorer 8 – Windows
  • Mozilla Firefox 3.5 – Mac
  • Mozilla Firefox 3.5 – Windows
  • Google Chrome – Windows (only works for textbox and select elements)
  • Safari – Mac (only works for textbox and select elements)
  • Safari – Windows (only works for textbox and select elements)

For the Webkit browsers (Safari, Chrome) it appears that the document.activeElement property will only be set if the element that has the focus is a textbox or a select element. Where the other browsers also report if a checkbox or a radiobutton has the focus.

This was my testing HTML file:


<html xmlns="">
		<link rel="stylesheet" href="c/style.css" media="screen,projection" type="text/css" />
		<script src="j/jquery-1.3.2.min.js" type="text/javascript"></script>
		<script src="j/index.js" type="text/javascript"></script>
		<input type="text" id="text-box" /><br />
		<input type="checkbox" id="checkbox" />
		<label for="checkbox">checkbox</label><br />
		<select id="select">
			<option value="1">Testing</option>
		</select><br />
			Current active element: <span id="current-active-element"></span>

With a little bit of javascript attached to it:

	setInterval("updateActiveElement();", 500);

function updateActiveElement()

This test page will write out the ID of the active element every 500 milliseconds so we can clearly see which element has the focus.

James Goodfellow has written a post about the property which is now, according to his post, part of the HTML 5 specification. For browsers that don’t support the property, James provides a workaround.

If you want to test it yourself, I uploaded the test page.