Iron3eagle
Iron3eagle

Reputation: 1077

Get HTML tags and text

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

Upvotes: 3

Views: 440

Answers (3)

mswieboda
mswieboda

Reputation: 1036

New jsFiddle: http://jsfiddle.net/EdD7U/2/

$("tr").each(function () {
    var colIndex = 0;

    $(this).find("td").each(function () {
        $(this).parent().parent().find('th')
            .each(function(index) {
                if (index == colIndex) {
                    var colHeader = $(this).prop("outerHTML");
                    alert(colHeader);
                }
            });

        colIndex++;
    });            
});

Basically, save the index of the tr you're in, and then grab a few parents up the dom (to table) and then find the th tags. For each th tag, only output the th of the index from the original tr. The variable you're trying to obtain is colHeader.

Upvotes: 0

deerchao
deerchao

Reputation: 10544

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());

Upvotes: 1

Ram
Ram

Reputation: 144739

You can use outerHTML property.

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

Or:

var html = this.outerHTML;

http://jsfiddle.net/Qy8GS/

Upvotes: 3

Related Questions