Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML tags and text

Tags:

html

jquery

I am currently working on creating a table that allows me to sort rows in ascending and descending order as well as click and drag columns around. I have that working, but I would like to improve it. Currently I'm getting the header and cell element text and then concatenating the HTML tags to the string:

var row = "<td>" + myData + "</td>";

What I want to know is if jQuery has a method/function that would allow me to get the text with the tags attached to just the one element.

I have tried .text() .html() .contents(); .parent().html(). The function .parent().html() is the closest to what I want, but it gives me all the rows with tags and text, as opposed to just the one I want.

So what I want to save in my variable is <th>First Column</th> not just First Column.

Here is a fiddle example of what I've tried and with basic HTML markup and links to the API I researched:

Fiddle

.text() .html() .contents() .parent()

Update:

For those curious why I'm doing this, here is my side project:

Table Sorter

like image 452
defaultNINJA Avatar asked Jan 19 '26 10:01

defaultNINJA


2 Answers

You can use outerHTML property.

var html = $(this).prop('outerHTML');

Or:

var html = this.outerHTML;

http://jsfiddle.net/Qy8GS/

like image 151
undefined Avatar answered Jan 21 '26 01:01

undefined


http://jsfiddle.net/aCTva/1/

$.fn.outerHTML = function () {
    var $t = $(this).eq(0);
    if ("outerHTML" in $t[0]) {
        return $t[0].outerHTML;
    } else {
        return $t.clone().wrap('<div></div>').parent().html();
    }
};


alert($(this).outerHTML());
like image 26
deerchao Avatar answered Jan 21 '26 02:01

deerchao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!