David
David

Reputation:

JQuery: Select html of an element, inclusive?

What's the best way to select the html of an element, inclusive? For example:

<div id="testDiv" class="testClass">
  This is just a test.
</div>

Whereas $('#testDiv').html() returns "This is just a test.", I would a selector that returns:

<div id="testDiv" class="testClass">This is just a test.</div>.

Thank you for your replies.

Upvotes: 5

Views: 1140

Answers (2)

kintsukuroi
kintsukuroi

Reputation: 1479

This is similar to the accepted answer, adding 2 improvements:

  1. A return line so that this is chainable. Example: $(select).outerHTML().css(x);
  2. Declared in such a way as to not interfere with other code. See https://learn.jquery.com/plugins/basic-plugin-creation/

Here is the code:

// add outer html selector
(function ($) {
    $.fn.outerHTML = function() {
        return $('<div>').append( this.eq(0).clone() ).html();
        return this;
    };
}(jQuery));

Upvotes: 0

Gumbo
Gumbo

Reputation: 655309

Try this jQuery.outerHTML() implementation.

jQuery.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
};

Upvotes: 5

Related Questions