1

Possible Duplicate:
Javascript isDOM — How do you check if a Javascript Object is a DOM Object?

I have the following simple function:

function do_smth(el){

    if(typeof el != 'object'){
        el = this
    }
    var val = $.trim(el.value)

     /**** some code here ****/

}

Sometimes it is binded to an element as an event

1)

element.onclick = do_smth

and sometimes it is used the following way

2)

do_smth(element)

both ways this should work good...

The problem is that I get the el as Event object in the first case, even if there are no arguments passed. So typeof el != 'object' does not work as expected.

How can I distinguish DOM element or Event?

Community
  • 1
  • 1
Dan
  • 55,715
  • 40
  • 116
  • 154

2 Answers2

1

To distingusih a DOM element do

if(el.nodeType)
Lime
  • 13,400
  • 11
  • 56
  • 88
  • Well if you certain it is an element and not a document or text node then you could do `el.nodeType===1` https://developer.mozilla.org/en/nodeType – Lime Aug 29 '11 at 18:48
  • nodeType returns a 1 for element nodes. https://developer.mozilla.org/en/nodeType – Trevor Aug 29 '11 at 18:48
  • Yeah, but event objects don't have a nodeType at all, so just querying if the value is existent should be fine. It would be more safe to do `if(el.nodeType===1)` though – Lime Aug 29 '11 at 18:51
  • Yup well there is a slight bug in [IE5](http://quirksmode.org/dom/w3c_core.html#t21) – Lime Aug 29 '11 at 18:54
1
function do_smth(el){
    el = el.nodeType == 1 ? el : this;
    var val = $.trim(el.value)
}
David Hellsing
  • 106,495
  • 44
  • 176
  • 212