简体   繁体   中英

How to get first td text from a tr by jquery

I want to get a text of cell in a tr row. The tr row has class attr and a data- attr. I select the tr row as

var k = $('tr[class="BatchTypesRow"][data-rowselected="true"]');

then

var m = k.children("td:first");    
var sBtype = m.text();    
alert(sBtype);    

the sBtype contains all cells' text in the row. I tried

var sBtype = m[0].text();    

that catches an exception.

So what is the problem here? If the cell is not the first cell in the row, how to do it?

Here, m itself is the first td of the row since var m = k.children("td:first");

So m.text() would not give the whole row as long as td:first is selected. If you use .children("td") then you would be getting the whole row in m.text() . So in your code,

var sBtype = m.text();    
alert(sBtype);

would actually give the First cell content.

If not the first cell, you would be using var m = k.children("td"); removing the keyword first . In this case m[0] would have the first cell, m[1] second and so on.

Correct me if am wrong, I believe this is how you got the exception, using m[0].text() would throw you an exception since m[0],m[1] are not JQuery object. They are HTMLTableCellElement Object.

To use it as a JQuery object, you would have to use $(m[1]).text() .

And if you know which element to be selected wrt its sequence, you can use

var m = k.children("td:nth-child(n)"); 

where you can replace n with the number so that you will select the nth td of the row.

Hope this helps.

$('tr.selected td:first-child').text();

Firstly, select the tr within which lies the text.for which you can use the class attr

$("tr.BatchTypesRow")

then traverse down the tree to get the td ie its children

$("tr.BatchTypesRow").children("td")

as you need the first child ,is the first td as you traverse through the selected tr ,it can be further written as

$("tr.BatchTypesRow").children("td:first")

if the text lies within a label inside the selected td

$("tr.BatchTypesRow").children("td:first").children("label").text();

will give you the desired text .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM