Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform element to string with jQuery

I don't need innerHTML i need innerHTML with enclosing tags. Lets write some example:

<div id="1" style="qwe"><span class="1"></span></div>
<div id="2" style="asd"><span class="2"></span></div>
<div id="3" style="zxc"><span class="3"></span></div>

I can get element by id:

$("#1")

And how can i get string like that:

<div id="1" style="qwe"><span class="1"></span></div>

Of course html() doesn't work becouse it will return only span.

like image 913
Fisher Avatar asked Feb 07 '12 12:02

Fisher


2 Answers

you could do something like this:

alert( $('#\\31 ').wrap("<div />").parent().html() )
$('#\\31 ').unwrap()
like image 105
meo Avatar answered Oct 13 '22 04:10

meo


Something like this should work fine:

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

var outer = $("#1").outerHTML();

Here's a working fiddle.

Additional Info

See http://www.yelotofu.com/2008/08/jquery-outerhtml/ for original article .

like image 21
James Hill Avatar answered Oct 13 '22 05:10

James Hill