Wednesday 20 January 2016

How to fix error - JavaScript runtime error: Unable to set property 'className' of undefined or null reference


Watch this example on YouTube:

To illustrate the issue here are my components involved in it
1. CSS
.ShowForm{
    border: 2px;
    visibility: visible;
    background-color: red;
    width:100px;
    top:200px;
    height:100px;
    left:100px;
}
.HideForm {
    visibility:hidden;
}


2. Html

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="JavaScriptPopup.aspx.vb" Inherits="VBTest.JavaScriptPopup" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles/StyleSheet1.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="HideForm" id="showDiv">
        </div>

        <div><asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" >Show Form</asp:LinkButton></div>
    </form>
</body>
</html>

3.Code Behind

Public Class JavaScriptPopup
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
        Dim sbTest As New StringBuilder()
        sbTest.Append("<script type=""text/javascript"">")
        sbTest.Append("document.getElementById('showDIV').className='ShowForm';")
        sbTest.Append("</script>")
        Page.ClientScript.RegisterStartupScript(Page.[GetType](), "show me", sbTest.ToString(), False)
    End Sub
End Class





to fix it replace
  sbTest.Append("document.getElementById('showDIV').className='ShowForm';")
with
  sbTest.Append("document.getElementById('showDiv').className='ShowForm';")

No comments:

Post a Comment