views:

105

answers:

5

How can I get the complete HTML code of the element I'm mouseovering or clicking? Using document.onmouseover = function(e){ can I get the full underlying HTML code of the element which triggered the event?

Right now, I am able to get the tag name or id or whatever. What I would like is the whole code.

For example; if I'm mouseovering a table, I would like to get the string: <table><tr><td></td></tr></table>

Is this possible?

+4  A: 

IE already has element.outerHTML

and this for others:

if (!('outerHTML' in document.documentElement)) {
    function getOuterHTML(element){
        var dummy = document.createElement('html');
        dummy.appendChild(element.cloneNode(true));
        var result = dummy.innerHTML;
        dummy.innerHTML = '';
        return result;
    }
}
else{
    function getOuterHTML(element){
        return element.outerHTML;
    }
}

you can use it like this:

 alert( getOuterHTML( document.getElementById("elementID") ) );
David Murdoch
Very nice :) !!! Thanks !
oimoim
+1  A: 

Do you mean just the structure, or the complete HTML code?

Just for the structure, you can use jQuery's children() function and iterate through them.

For the complete code, Internet Explorer has a property named outerHTML. To make this work in Firefox have a look at http://snipplr.com/view/5460/outerhtml-in-firefox/.

Tom
not tagged with jQuery.
David Murdoch
To David : do I need jQuery ?To Tom : I will try this out. Thanks. We'll see if it works :)
oimoim
nope. no need for jquery here.
David Murdoch
A: 

You can clone the node, then insert it to another node and get the innerHTML for the parent node.

rahul
+2  A: 

Generally, you would wrap the element with another, and call innerHTML on the wrapper, e.g.:

   document.onmouseover = function(e){
       var el = e.target;
       var p = document.createElement('p');
       p.appendChild(el.cloneNode(true));
       console.log(p.innerHTML);
   }

I would go with @David Murdoch's solution, which seems to be more complete.

karim79
+1  A: 

It's unclear what you're really asking, but I suspect you just want to get a string containing the HTML for the element you are mousing over. To that end, try the following:

function getMouseOverHTML(event) {
  event = event || window.event;
  return event.currentTarget.parentNode.innerHTML;
}

Then you can do whatever you like with that string of HTML markup.

Robusto
Nice one too, but I prefer the outerHTML answer below.Thanks !
oimoim