Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 878
Wim Ombelets Avatar asked Jun 05 '15 07:06

Wim Ombelets


2 Answers

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.

like image 140
RichieHindle Avatar answered Oct 20 '22 01:10

RichieHindle


You can use directly this to access outerHTML of the current object instead of indirectly going through $(this) as this represents the DOM object (which has outerHTML property) whereas $(this) represents jQuery object.

this.outerHTML
like image 39
Adil Avatar answered Oct 20 '22 01:10

Adil