www.webdeveloper.com
Results 1 to 5 of 5

Thread: how do you check if an object exists

  1. #1
    Join Date
    Mar 2010
    Posts
    281

    how do you check if an object exists

    Hi,
    i'm trying to check if a certain button exists on the page.

    i've both of these and they always return false,
    uggg....one of those days,....the simplest things..!

    PHP Code:
    if(document.getElementById['testdiv']) {
        
    alert('it exists');
        
    //do something
            
    } else {
        
    alert('it does not exist');
        
    //do something else
        

    i've also tried simply,

    PHP Code:
    if('testdiv') {} 
    i also put at the bottom of the page so everything was loaded and also inside of a
    PHP Code:
    $(document).ready(function() { 

  2. #2
    Join Date
    Jun 2012
    Location
    FL, USA
    Posts
    48
    try
    Code:
    myobject = document.getElementById('testdiv');
    if (typeof myobject != 'undefined')
    { // this means it exists and has a defined value}
    else
    { // this means the type of your object was undefined. i.e. doesn't exist or has no value assigned to it }

  3. #3
    Join Date
    Mar 2011
    Posts
    61
    When you use document.getElementById on a non existing ID it returns 'null', not 'undefined'.
    Code:
    if(document.getElementById('testdiv') != null) { 
      // exists
    } else { 
      // doesn't exist
    }

  4. #4
    Join Date
    Nov 2007
    Posts
    409
    The error is that you are using ['testdiv'] instead of ('testdiv')

    Change your square brackets to parenthesis and it works fine:
    Code:
    if(document.getElementById('testdiv')) {
        alert('it exists');
        //do something
            } else {
        alert('it does not exist');
        //do something else
        }

  5. #5
    Join Date
    Mar 2010
    Posts
    281
    crimeny!!, thanks all! much appreciated

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles