i need to get the second td span value based on tr id
`
<table><tr id="1">
<td style="width:150px;"><span id="1">C </span></td>
<td><span style="width:800px;">hello world</span></td>
<td><input type="checkbox" name="1" onclick="KeywordText(1);" value="1"></td>
</tr>
<tr id="2">
<td style="width:150px;"><span id="2">Dot Net </span></td>
<td><span style="width:800px;">Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai</span></td>
<td><input type="checkbox" name="2" onclick="KeywordText(2);" value="2"></td>
</tr></table>
i need to get the second td span value based on tr id
`
<table><tr id="1">
<td style="width:150px;"><span id="1">C </span></td>
<td><span style="width:800px;">hello world</span></td>
<td><input type="checkbox" name="1" onclick="KeywordText(1);" value="1"></td>
</tr>
<tr id="2">
<td style="width:150px;"><span id="2">Dot Net </span></td>
<td><span style="width:800px;">Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai</span></td>
<td><input type="checkbox" name="2" onclick="KeywordText(2);" value="2"></td>
</tr></table>
Share
asked Mar 19, 2014 at 15:35
RajRaj
552 silver badges5 bronze badges
2
- You need to get the second td that has a span, or just the span in the second td ? – Robin Leboeuf Commented Mar 19, 2014 at 15:36
- You shouldn use the same id on more then one object... your tr and span object have the same id in your example – Ra Mon Commented Mar 19, 2014 at 15:39
4 Answers
Reset to default 5This assumes you want the second span
JavaScript:
var row = document.getElementById("rowId");
var spans = row.getElementsByTagName("span");
var secondSpan = spans[1];
jQuery:
var secondSpan = $("#rowId span:eq(1)");
It you want the span inside the second table cell
JavaScript:
var row = document.getElementById("rowId");
var cells = row.getElementsByTagName("td");
var spans = cells.getElementsByTagName("span");
var secondSpan = spans[0];
or with querySelector
var span = document.getElementById("rowId").querySelector("td + td > span");
jQuery:
var secondSpan = $("#rowId td:eq(1) span");
And spans do not have a value, you either what its html or its text.
JavaScript:
var text = secondSpan.innerHTML;
jQuery:
var text = secondSpan.html(); // or secondSpan.text();
function KeywordText(id) {
var td = document.getElementById(id).cells[1];
console.log(td.firstChild.innerHTML); // "hello word" if id == 1
}
example: http://jsfiddle/n2t4Z/
Strictly speaking, you can do it like this:
getSpanValueByRowId(1);
function getSpanValueByRowId(rowID) {
var row = document.getElementById(rowID);
var cells = row.getElementsByTagName("td");
var span = cells[1].getElementsByTagName("span")[0];
return span.innerText;
}
Although you could use jQuery to get it, it would look like this:
function getSpanValueByjQuery(rowID){
return $("#"+rowID + " td:nth-child(2) span").text();
}
Using jQuery:
var getvalue=$(this).closest('tr').find('td:eq(1) span').val();
alert(getvalue);