In the Html table, can I get the id of elements located in another row?

I have this HTML table structure where I am defining various strings (tr):

<table>
    <tr><td><button id="1" onclick="getid()"></button></td></tr>
    <tr><td><button id="2" onclick="getid()"></button></td></tr>
    <tr><td><button id="3" onclick="getid()"></button></td></tr>
    <tr><td><button id="4" onclick="getid()"></button></td></tr>
    <tr><td><button id="5" onclick="getid()"></button></td></tr>
</table>
<script>
    function getid(){
        alert($(this).closest('[id]'));
    }
</script>

      

When any button is clicked, I can get the ID of the button above the line and below the line.

Which I don't get. What's going wrong?

+3


source to share


1 answer


Change onclick

the pass handler this

as a parameter in Html and then use methods .next()

and .prev()

jQuery as below: -

HTML: -

<table>
    <tr><td><button id="1" onclick="getid(this)"></button></td></tr>
    <tr><td><button id="2" onclick="getid(this)"></button></td></tr>
    <tr><td><button id="3" onclick="getid(this)"></button></td></tr>
    <tr><td><button id="4" onclick="getid(this)"></button></td></tr>
    <tr><td><button id="5" onclick="getid(this)"></button></td></tr>
</table>

      



jQuery: -

<script>
function getid(elem){
    alert($(elem).closest('tr').prev('tr').find('button').attr('id'));
    alert($(elem).closest('tr').next('tr').find('button').attr('id'));
}
</script>

      

DEMO

+3


source







All Articles