views:

722

answers:

4

to debug some javascript code, I am looking for javascript code (preferably just js, without libraries and dependencies) that can highlight a div or span (probably by putting over it a div or span of the same size and shape with a bright color and some transparency).

I pretty sure it can be done, but I don't know how to start.

CLARIFICATION

I need to put a semi transparent div on top of my element. Modifying the background or adding borders will not help as my elements have themselves backgrounds and borders.

+2  A: 

If you're debugging in a browser that supports the CSS outline, one simple solution is this:

myElement.style.outline = '#f00 solid 2px';
Blixt
A: 

Do you use Firebug? It makes it very simple to identify dom elements and will highlight them in the page as you walk through the dom.

seengee
+4  A: 
element.style.backgroundColor = "#FDFF47";

#FDFF47 is a nice shade of yellow that seems perfect for highlighting.

Edit for clarification: You're over-complicating things. If you ever want to restore the previous background color, just store element.style.backgroundColor and access it later.

Eli Grey
Doubt you'll get much simpler or effective than that.
Jim Davis
+1  A: 
function highlight(element) {
    var div = highlight.div; // only highlight one element per page

    if(element === null) { // remove highlight via `highlight(null)`
        if(div.parentNode) div.parentNode.removeChild(div);
        return;
    }

    var width = element.offsetWidth,
        height = element.offsetHeight;

    div.style.width = width + 'px';
    div.style.height = height + 'px';

    element.offsetParent.appendChild(div);

    div.style.left = element.offsetLeft + (width - div.offsetWidth) / 2 + 'px';
    div.style.top = element.offsetTop + (height - div.offsetHeight) / 2 + 'px';
}

highlight.div = document.createElement('div');

// set highlight styles
with(highlight.div.style) {
    position = 'absolute';
    border = '5px solid red';
}
Christoph