Barry Hamilton
Barry Hamilton

Reputation: 973

jquery traverse through row getting span class and title

I have a table each row has an id and several td's containing spans

e.g

<tr id="row"><td><span class="first name">myfirstname<span class="surname">mysurname</span></td><td><span class="street">mystreet</span><span class="town">mytown</span></td>

What I wan't to do is when passed a rowid traverse the row and create a key value array of the span classnames and the span values.

currently I can go find each thing individually which is very cumbersome.

Upvotes: 0

Views: 670

Answers (4)

jorgebg
jorgebg

Reputation: 6600

You should send a code sample to have more accurate responses. Try this:

var values = new Object();
$("#row").filter("td span").each(function(){
    values[$(this).attr("class")] = $(this).text();
});
alert(values.surname);

Upvotes: 0

gdoron
gdoron

Reputation: 150293

Your markup should be fixed a bit:

<table>
    <tr id="row1">
        <td>
            <span class="first name">myfirstname </span>
            <span class="surname">mysurname</span>
            </td>
                <td>
                    <span class="street">mystreet</span>
                    <span class="town">mytown</span>
        </td>
    </tr>
</table>

You didn't close the <span> and <tr>

CODE:

function getSpansData(rowId) {
    var map = {};
    $('#' + rowId + ' span').each(function() {
        map[this.className] = this.innerHTML;
    });

    return map;
}

getSpansData('row1');

Live DEMO

Upvotes: 2

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

var map = {};
$("#row_id td span").each(function() { 
  map[$(this).attr("class")] = $(this).html(); 
});

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

function traverseRow(id) {
    var arr = {};
    $('td span', 'tr#' + id).each(function() {
        arr[this.className] = this.innerHTML;
    });
    return arr;
}

traverseRow('row');

Upvotes: 1

Related Questions