javascriptjqueryvisual-studio-2013intellisensejavascript-intellisense

Why can't you call outerHTML on $(this)?


When you want to get the HTML of an entire DOM element (wrapper included), you can do the following (as explained here):

$('#myElementId')[0].outerHTML

But what you can't do is call outerHTML on $(this) inside e.g. a click listener or selector function body scope:

$(this).outerHTML //Doesn't complete in IntelliSense, returns undefined in browser

or

$(this)[0].outerHTML //Correction, this DOES work, but it doesn't complete in IntelliSense

because IntelliSense won't show innerHTML or outerHTML in those circumstances, although with vanilla JavaScript you can do:

document.getElementById($(this).attr('id')).outerHTML

So... what's up with that?


Solution

  • outerHTML is a DOM property; jQuery doesn't expose all DOM properties.

    If you have a jQuery object, you can only directly access those properties and methods that jQuery exposes, and vice versa for DOM objects.

    In object-oriented terms, jQuery objects don't inherit from DOM objects, they contain them.

    Saying $x[0] gets you the DOM object for the first element represented by a jQuery object.