Sk Asraf Sk Asraf - 6 months ago 13
jQuery Question

how can get span id from table data in jquery

I have a

table
tr
and
td
. In between the table data there is a
span
that I want to take the ID from.

In my jquery code, it's not returning any value from
span
id.

How can get
span
id?

My HTML

<table id="t1" border="1">
<tr>
<td><span id="111" class="f1" onclick="subtract();">Subtract</span></td>
</tr>
<tr>
<td><span id="222" class="f2" onclick="subtract();">Subtract</span></td>
</tr>




My jQuery

$(document).ready(function () {
$("#t1 span").click(function () {
var a = $(this).id();
alert(a);
})

})

Answer

Without jQuery you can get it by passing the span element to your function subtract:

function subtract(elem) {
    var id = elem.id
    console.log(id);
}
<table id="t1" border="1">
    <tr>
        <td><span id="111" class="f1" onclick="subtract(this);">Subtract</span></td>
    </tr>
    <tr>
        <td><span id="222" class="f2" onclick="subtract(this);">Subtract</span></td>
    </tr>
</table>

Comments