0

I was just about to set onclick event for my element in javascript, but I wonder which of these two options is more efficient:

document.getElementById(myid).onclick = function(e){...}

or

document.body.onclick = function(e){if(e.target.id == myid)...}

Is there any difference? Is one of these declarations processed slower?

6
  • Efficient in what sense? The second takes more time to type, so its less efficient in that sense. Commented Sep 9, 2014 at 15:51
  • The first is faster....you are zeroing in on the ID of interest plus there is no conditional statement to detect the ID like in option #2 Commented Sep 9, 2014 at 15:52
  • @TheOneandOnlyChemistryBlob can you prove this in a test? Commented Sep 9, 2014 at 15:53
  • Sure...go ahead and use jsperf... Commented Sep 9, 2014 at 15:54
  • 1
    @SaintLouisFella it's good to keep efficiency in mind because in the long run you will create code where you (as jQuery says) "write less, do more" but just remember that TJHeuvel is correct and the gains you get from these microoptimizations will be very very small....for big speed gains, minimize queries, use descendant selectors, use css whenever possible, and more Commented Sep 9, 2014 at 15:58

2 Answers 2

1

Its recommended that you use AddEventListener instead of binding to OnClick.

As for efficiency i'm not sure what you are worrying about. If its performance you should measure your issues and solve those instead of wondering about possibly minute details.

Sign up to request clarification or add additional context in comments.

Comments

1

If you use document.body.onclick = function(e){if(e.target.id == myid)...} you are listening to ALL the click of the mouse, include buttons, links, ecc ecc. This could slow down your site (expecially on mobile device or old computers).

Use document.getElementById(myid).onclick = function(e){...} isn't bad, but I suggest you to use document.getElementById('...').addEventListener("event", function(event) {...});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.