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?

1
  • 1
    You should use the function in a consistent way imo. Commented Aug 29, 2011 at 18:47

2 Answers 2

1
function do_smth(el){
    el = el.nodeType == 1 ? el : this;
    var val = $.trim(el.value)
}
Sign up to request clarification or add additional context in comments.

3 Comments

el will be the event object when used as event handler.
no, el is always defined, it can be an event
right, I misunderstood the question. Updated...
1

To distingusih a DOM element do

if(el.nodeType)

4 Comments

Well if you certain it is an element and not a document or text node then you could do el.nodeType===1 developer.mozilla.org/en/nodeType
nodeType returns a 1 for element nodes. developer.mozilla.org/en/nodeType
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
Yup well there is a slight bug in IE5

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.