ryanv
ryanv

Reputation: 75

Fastest way to check an element exists before calling a function using the elements value as parameter in JavaScript

I want to check if an element exists in the DOM, if it does, then call a function using the element's value as a parameter. eg:

if(document.getElementById('msg')) displayMsg(document.getElementById('msg').value);

Is this the fastest way to achieve this?

Upvotes: 0

Views: 601

Answers (2)

Slai
Slai

Reputation: 22876

If the id is unique enough, the element can be accessed directly from window.msg :

window.msg && alert(msg.value)
window.msg1 && alert(msg1.value)  // window.msg1 is undefined
<input id=msg value=hi>

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075209

Is this the fastest way to achieve this?

No, but it's very, very, very, very fast.

The fastest way is to remember the result of the first getElementById call rather than repeating it:

var msg = document.getElementById('msg')
if(msg) displayMsg(msg.value);

getElementById is very, very, very, very fast, and you'd have to be doing this hundreds of thousands of times — possibly millions — in a tight loop for any human to perceive the difference.

Upvotes: 1

Related Questions