Search code examples
javascriptc#getelementbyid

How do get id of calling element for JavaScript onclick


I have a GridView where each row has information and when the user clicks on the row more, related, information is displayed in a separate DIV (this works) but when I want to access row (to change/add css classes on click) I cannot target the row. How do I target the row that the JavaScript onclick event is assigned to?

Here is a very stripped down version of the code:

protected void vd_gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {
        e.Row.Attributes.Add("onclick", "showTest(this)");
    }
}

Here is the JS that is called onclick:

<script type="text/javascript">
    function showTest(test) {
        // var rowTest1 = document.getElementById(this);
        // var rowTest2 = document.getElementById(this.id);
        // var rowTest3 = document.getElementById(test);
        // var rowTest4 = document.getElementById(test.id);

        var row = document.getElementById(test.id);
        var currentClass = row .className;

        row.className += "testClass";
    }
</script> 

When debugging the page this is the error generated:

Empty string passed to getElementById().

Solution

  • In the end this is what I did:

    row.Attributes["id"] = gv.ID + "_row_" + e.Row.RowIndex.ToString();
    

    And get the reference here:

    var row = document.getElementById(test.id);