SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    what's the best way to make sure an element exists?

    Hello,

    Before adding / removing a class (just an example from the top of my head) I always do the following:

    Code:
    if ( typeof(myelement) != "undefined" && myelement !=  null && typeof(myelement) == 'object' ) {
    //add / remove class
    }
    I feel like this is not a good approach. What are the checks you have to do to make sure an element is in the DOM and can be used for various purposes? Would =='object' be enough?


  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Generally i just check to ensure that the value is not equal to 'undefined'.

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Commonly duck typing is used to perform checks such as this, where we just check the important properties to ensure that it's close enough to being an element.

    For example:

    Code javascript:
    function isElement(elem) {
        if (typeof HTMLElement === 'object') {
            return elem instanceof HTMLElement;
        }
        return elem &&
            typeof elem === 'object' &&
            elem.nodeType === 1 &&
            typeof elem.nodeName === 'string';
    }

    If the browser has HTMLElement object support, a simple test against that is good enough.

    If not though, we check first that the object exists and that it is an object before checking for a couple of obvious properties that an HTML element should have. If they're there, it's close enough to being an element for us to accept that it is one.
    Last edited by paul_wilkins; Apr 11, 2012 at 13:14.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I find this interesting because I always thought just checking the nodeType was sufficient. Are there instances where that can trip you up?

  5. #5
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks

    Why don't you declare the obj variable? Should it be elem?

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Thanks

    Why don't you declare the obj variable? Should it be elem?
    Yes it should, and has been corrected. Thanks for catching that.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Raffles View Post
    I find this interesting because I always thought just checking the nodeType was sufficient. Are there instances where that can trip you up?
    Just checking the nodeType property can trip you up if no object actually exists, for then the script stops executing with an error.

    Checking that the object exists first does tend to be mandatory.
    Checking that it's an object is not strictly necessary, but it does help others coming across the code to know that you expect it to be an object from that point onwards.
    Checking the nodeType also tends to be mandatory, if you want to avoid matching other nodes such as text nodes, or comment nodes.

    From what I understand though, that's not quite enough in some browsers when working with elements that belong to other windows or frames, which is why nodeName is also used.
    It would be useful though if we had some tests to confirm that this is actually the case.

    And while it is possible to pass in something that is not an element and will in some older browsers be mistaken for one, such as:

    Code javascript:
    isElement({
        nodeType: 1,
        nodeName: 'P'
    });

    We are not attempting to remove all doubt here. Instead, we are looking to see if it's close enough to what an element should be, If it's close enough then we'll accept that it as it is. That's duck typing for you
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  8. #8
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To answer the original OP, if you are looking for an element node do not just check for typeof=='object',
    because null is an object, and null is what you get if you look for something specific in the dom that isn't there,
    like trying getElementById on an element that hasn't been appended to the document, or previous/nextSibling when you are at the first/last child.

    if(node && node.nodeType==1) is good enough for most of us.


Bookmarks

Posting Permissions

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