HTML element ids and $ scoped backbone.js object

I inherited a moderately complex code base that makes heavy use of jQuery, backbone.js, and ejs templates. Many of the templates in this codebase have more or less HTML structure:

<div id="foo">
  <div id="bar"></div>
  <span id="baz"></span>
</div>

      

... The view code that supports these templates contains many features such as:

function doSomeStuff() {
  this.$("#foo").hide();
}

      

...

If more than one of these views is present in the DOM, for example if I represent a Backbone collection, this will cause the DOM to contain multiple elements with the same ID. According to the W3C spec which calls document.getElementById()

undefined behavior to manifest, and I'm pretty sure jQuery uses this feature under the hood. But the view code does indeed work correctly as it is currently written.

I noticed that this code is using the jQuery scope instance provided by Backbone . My question is, can I rely on this scoped instance to always select only the elements I want? Or am I just lucky here and really need to rewrite a lot of this code to do the right thing and use classes instead of ids?

+3


source to share


1 answer


In the world of web development, there are two sets of rules: the rules defined by the W3C (i.e. the specifications) and the rules defined by the browsers (i.e. what Google / Microsoft / Mozilla wants). For years, attributes id

have been a noticeable difference between the two sets of rules: the W3C says attributes id

must be unique, but the browser didn't care.

This means that Backbone, jQuery, or any other tool (which is not a W3C validator) will not care about multiple instances of the same attribute id

. This means Backbone / jQuery won't get in your way, but it also means they are not the source of your problem.



My personal recommendation is: Don't bother with a few ID attributes id

, because they won't hurt anything. Browsers will happily treat them as classes, and all jQuery styles / selectors / etc. will continue to work.

Instead, focus on taming other aspects of your newly inherited complex codebase, aspects that cannot be so easily ignored. Then, once you have dealt with all the meaningful, you can go back and change any id

that is repeated in the attribute class

. Both before and after this, Backbone, this.$

and jQuery in general, should work fine.

0


source







All Articles