1

To reference this DOM element:

<input id="chkBxCheezDoodles" type="checkbox" />

in a Windows 8 JS app, I can do this:

document.getElementById("chkBxCheezDoodles").checked = true;

or this:

chkBxCheezDoodles.checked = true;

When (if at all) is getElementById preferred ahead of the direct reference? Is it considered "cleaner" to use getElementById?

2 Answers 2

3

My preference is to use getElementById, rather than relying on the variable to be projected into the global namespace. This leads to no issues with similar named variables, clashes etc.

IMHO, I try not to use ID at all, and use querySelectors instead, either with a custom attribute or specific CSS classes.

1
2

I agree with Dominic. I suspect it may be more performant if you use getElementById instead of querySelector, but I usually don't care about those nickel and dime time savings. You don't want to be typing document.querySelector all the time and I don't like having to decide between document.querySelector and querySelectorAll each time. "Let's see am I expecting one thing back or a few things back?" So I wrapped them both in a function I call query in my ocho.js library. I usually bring it into my app into the global namespace as simply "q". That way I can always do q("#charlie") to get the element called "charlie" or q(".large") to get all of the elements with the class of large. If there's just one it returns the DOM element. If there are multiple then it returns a vanilla array. This makes my life easier. Then I can do...

q(".large").forEach(function(el) { el.style.fontSize = 'xx-large'; });
1
  • Thanks, I'll definitely take a look at the ocho.js library. Hoping to see it as a Nuget package some time in the future.
    – anderaus
    Dec 1, 2012 at 11:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.