GetElementById find element/exists Javascript?

Posted on 2007-10-05
Last Modified: 2009-12-16
I am coding a .NET page C# and I have a javascript function which I need to check for before I do anything with it.  It is a gridview but it is empty when the page loads.  No matter what I do when checking to see if the grid exists, I get the 'object required' error.  Why?  

if (document.getElementById('foo') == null) {alert('foo is missing!');}
if ( ! document.getElementById('foo')) {alert('foo is missing!');}

Is there another way to check for this id foo which will work and not return the object required error?
Question by:ksummers
    LVL 23

    Expert Comment

    by:Jens Fiederer
    Assuming you are posting part of a SCRIPT rather than trying to do C#, both look perfectly reasonable.

    Can you post a bit more code?  I am guessing that you have identified the wrong line.

    Author Comment

    Well, here is some of my code.  I had to edit it to take out some work related private stuff.  Basically what happens, is when the page loads there are some dropdowns to select search criteria.  I have a function hideGrid() to hide the grid when the dropdown is selected for a new search.  Well, when the page loads, the grid is empty and not there.  After the first search tho, the dropdowns work fine with the function because the grid is there because the element is found.  Hopefully that makes sense.  Here is some code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
    <html xmlns="">
    <head id="Head1" runat="server">
        <link rel="stylesheet" type="text/css" href="ReportViewerStyles.css" />
        <SCRIPT LANGUAGE="JavaScript" SRC="CalendarPopup.js"></SCRIPT>
        <script language="javascript" type="text/javascript">
    function hideGrid()
    if ( ! document.getElementById('gvReportInstances')) {      alert('grid is missing!');}
    //I am trying to find the element so I can hide when the drop down is clicked for a new search.                                      
    //document.getElementById("gvReportInstances").style.display = "none";
    //document.getElementById("btnNewSearch").style.display = "none";
        <form id="Form1" runat="server">
        <div id="ScrollDiv" style="border : solid 0px #000000; background : #ffffff; color : #000000; padding : 0px; width : 100%; height : 350px; overflow : auto; ">
                                                <asp:GridView ID="gvReportInstances" runat="server" HorizontalAlign="Center" Width="775px"
                                                    PageSize="25" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
                                                    CellPadding="0" EmptyDataText="No reports meeting the specified criteria were found.  Modify the search criteria and try again."
                                                    BorderStyle="None" BorderWidth="0px" CaptionAlign="Bottom" OnPageIndexChanging="gvReportInstances_PageIndexChanging" OnRowCommand="gvReportInstances_RowCommand" DataKeyNames="InstanceKey,FileName,OfflineZipFile">
                                                    <HeaderStyle CssClass="SubMenu" BorderStyle="None" />
                                                    <AlternatingRowStyle BackColor="AliceBlue" BorderStyle="None" BorderWidth="0px" />
                                                      <asp:ButtonField ButtonType="Image" ImageUrl="~/Resources/mag_glass.gif" Text="View" CommandName="View" />
                                                        <asp:TemplateField HeaderText="Client">
                                                                <asp:Label ID="lblClientName" runat="server" Text='<%# Eval("ClientName")%>'></asp:Label>
                                                        <asp:TemplateField HeaderText="Run Date">
                                                                <asp:Label ID="RunDate" runat="server" Text='<%# Eval("RunDate")%>'></asp:Label>
                                                        <asp:TemplateField HeaderText="Parameters">
                                                                <asp:Label ID="Parameters" runat="server" Text='<%# Eval("ParamName")%>'></asp:Label>
                                                    <RowStyle BorderStyle="None" />
                                                    <EditRowStyle BorderStyle="None" />
                                                    <SelectedRowStyle BorderStyle="None" HorizontalAlign="Left" />
                                                <asp:Label ID="MaxRowLabel" runat="server" ForeColor="Red" Width="584px"></asp:Label>
    LVL 19

    Assisted Solution

    by:Jim Cakalic
    First, right click in the browser and choose View Source for the page in question. Find the HTML element corresponding to the GridView and be sure that the ASP.NET id you gave the control is the same as the HTML id. ASP.NET sometimes changes the value so you may not be finding the element in the DOM.
    LVL 23

    Accepted Solution

    There is NOTHING wrong with the hideGrid function as it stands....I cut and pasted it into a new html page, and it functioned....but if you did not have the last two lines in it commented OUT, those lines WOULD generate an "object required" error.

    If that is what was doing it, you want to put a RETURN statement inside your
    if ( ! document.getElementById('gvReportInstances')) {      alert('grid is missing!'); return;}

    otherwise you get the alert - and then STILL get the error.
    LVL 23

    Expert Comment

    by:Jens Fiederer
    I think it is VERY likely the error was originally caused by the lines commented out in the last code sample.
    LVL 23

    Expert Comment

    by:Jens Fiederer
    Considering that he SAID that the code was edited, did not assure us that the code as presented had actually been RUN - and that, with the code as IS, the error originally cited demonstrably does NOT occur, this seems the most probably cause to me.

    Of course, when the Asker abandons the question, there is no way to tell for sure.

    Author Comment

    I can't remember exactly why we ended up not going with the JavaScript when the page loaded.  I think because the grid was not visible 'til AFTER a search was done, so we kept getting the error in the page_load.  Basically, I think we modified the datasource of the grid whenever the dropdown was selected like this:

        gvReportInstances.DataSource = null;

    And the grid disappeared.  I can't remember because this was a few months ago.  Sorry I did not keep up with the thread, but you guys were great.  Thanks.

    Author Comment

    b0lsc0tt, thank you.  sorry about that.  you were included in the split when i checked multiple solutions accepted.
    LVL 54

    Expert Comment

    Forced accept as detailed in http:#20537502 .

    EE Zone Advisor

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
    Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
    Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
    This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    24 Experts available now in Live!

    Get 1:1 Help Now