Javascript – How to highlight HTML element on mouse click

domhtmljavascriptmouseevent

Is it possible to write code in JavaScript that highlights the borders of the HTML element on which the mouse pointer stands (or clicks), in a similar way to what Firebug does, but without the use of a browser extension but rather rely on JavaScript alone?

If so, is it possible to get the relevant element from HTML code after the mouse click on element?

[edit] Thanks for the answers! is it possible to run those examples on external page (rather than on a page that I created) without the use of things like GreaseMonkey?

Best Solution

Here is a simple example. You should be able to build upon this:

document.onclick = function(e) {
    var event = e || window.event;

    // this is the element you want:
    var target = e.target || e.srcElement;
}

This method would probably be more preferred:

var hilightElement = function(e) {
    var event = e || window.event;

    // this is the element you want:
    var target = e.target || e.srcElement;
};

if (document.addEventListener){
    document.addEventListener('click', hilightElement, false);
} else if (document.attachEvent){
    document.attachEvent('onclick', hilightElement);
}