简体   繁体   中英

Get the parent of the clicked item with javascript

Hello Im trying to get the id of tr based on td click.

This my code for the button:

while ($stmt->fetch()) 
    {

         echo'<tr id="'.$id.'">
        <td><button type="button" onclick="removeSet(this)"><img src="images/program/trash.png"></button></td>

        </tr>';

    }

My javascript code:

function removeSet(cell)
{

  var id = cell.parentNode.getAttribute('id');

  alert(id);

}

My problem is that I get this error:

Uncaught TypeError: Cannot read property 'parentNode' of undefined

Use this function instead:

function removeSet(cell)
{

  var id = cell.parentNode.parentNode.getAttribute('id');

  alert(id);

}

The problem was that your function got the parent of the button (a td), not the parent of the td (a tr).

In order to get the id of the tr, you need the parent of the parent of the button.

You forgot to put a td in your tr.

this is the html syntax you should be using:

<table>
    <tr id="customId">
        <td>
            <button type="button" onclick="removeSet(this)">
                <img src="images/program/trash.png"/>
            </button>
        </td>
    </tr>
</table>


and this is the javascript code:

function removeSet(cell) {
    var id = cell.parentNode.parentNode.getAttribute('id');
    alert(id);
}

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