Enjoyted
Enjoyted

Reputation: 1151

Getting the cell of a <tr> that has particular className

What i'm trying to do is to get the cell of this where the classname is "revision_id".

<tr>
    <td class="supplierOrderId">10790</td>
    <td class="revision_id">#7</td>
    <td class="supplier">DGI Developpement </td>
    <td class="quantity">80</td>
    <td class="stock">0</td>
    <td class="purchase_price">10.00</td>
    <td class="comments"> </td>
</tr>

I managed to do it this way :

revision = this.parentNode.parentNode;
revisionId = revision.cells[1].innerHTML.replace( /[^\d.]/g, '' );

(cause I wanna get the int of the string)

iRevisionId = parseInt(revisionId);

Is there a more proper way to do it, with the given className ? Because in the case where someone adds a cell before mine in the future, my code is going to be "deprecated".

Hope i've given all the details,

Thanks by advance.

// More Details //

The problem with most answers is that they work only if I have 1 <tr>. Once I get multiple, it gets every revisionID like this :

console.log(result) -> #1#2#3#4

(if I have 4 <tr> for exemple)

So this is why I am getting the GOOD one like this : revision = this.parentNode.parentNode; // outputs the good <tr>

but after that, I can't get the with the given className.

Upvotes: 0

Views: 69

Answers (5)

Jai
Jai

Reputation: 74738

Well if you want it with jquery then you can use .filter() method:

 var text = $('td').filter(function () {
     return this.className === 'revision_id';
 }).text().slice(1);
 text = +text; // conversion for int
 alert(text);

Demo

Upvotes: 0

roobeedeedada
roobeedeedada

Reputation: 521

Depends on whether you can use jQuery or not.

Pure JavaScript

With pure JS, provided you're using a modern browser, you can use the getElementsByClassName function. For the purpose of this demonstration, I've assumed you have an ID on your table you can use.

var myClassName = 'revision_id';
var table = document.getElementById('mytable');
// the desired TD
var td = table.getElementsByClassName( myClassName ) );

See Mozilla's docs on getElementsByClassName.

Also, this answer works with backwards compatibility.

jQuery

Of course, this becomes easier with jQuery:

var $td = $('#mytable td.revision_id');

Demo here: http://jsfiddle.net/uJB2y/1/

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you can do via jquery like this:

 var value= parseInt($(".vision_id").text().match(/[0-9]+/g)[0]);

FIDDLE EXAMPLE

Upvotes: 0

Sridhar Narasimhan
Sridhar Narasimhan

Reputation: 2653

if this is tr

var data = $(this).children(".revision_id").text()

Upvotes: 1

Mivaweb
Mivaweb

Reputation: 5712

Using the text() method, you can get the text inside your td element. After that just parse it like you did with parseInt()

$(function() {
    var quantity = $('tr td.quantity').text();
    console.log(parseInt(quantity));
});

Upvotes: 0

Related Questions