I'm a front-end developer, and I'm worried about the best way to target my DOM.
Let's imagine a tiny form to create a new zombie :
<h1>Add a new zombie</h1>
<form id="create-zombie">
<input id="zombie" type="text" name="zombie" />
<input id="lvl" type="text" name="lvl" />
<button type="submit">Add</button>
</form>
...and if I want to get the values of zombie and lvl, I will code something like this:
class Zombie_Add extends Controller
# Dom References
el:
'form': '#create-zombie'
'zombie': '#zombie'
'lvl': '#lvl'
run: ->
#on 'submit', #el.form, #validate
validate: (e) =>
e.preventDefault()
zombie = $(#el.zombie).val()
lvl = $(#el.lvl).val()
module.exports = Zombie_Add
That's "ok" and it does the job, but I have some problems with that "structure" :
If somebody touches the DOM and removes an ID, I'm just fucked, it breaks my code (Captain Obvious spotted !)
For more complicated selectors, it's just a mess (I'm thinking about some stuff like that [name^="dummy-"] input:first). I guess it's easy to imagine how shitty the names of el are.
Anyway, what I want to learn today is what's the best way to target the DOM from JS. Is it better to use IDs, class values or, data-* attributes? How we can prettify a selector with plain English, etc...
If somebody touches the DOM and removes an ID, I'm just ****ed, it
breaks my code (Captain Obvious spotted !)
The best way to target a single, unique element in the DOM is with an ID like you are doing with zombie and lvl. It is both fast to execute and simple to code.
It is a given that if someone messes with the id values in your HTML, that will break your Javascript. That's just the way it is. Anyone messing with your HTML has to be smart enough to know that an ID value is there for a reason so if they want to change that or remove it, then it is their responsibility to find someone who can make corresponding changes in the Javascript. That's just the way it is.
For more complicated selectors, it's just a mess (I'm thinking about
some stuff like that [name^="dummy-"] input:first). I guess it's easy
to imagine how ****ty the names of el are.
The same goes for more complicated selectors. Like it or not, a modern web page is a melding of server-side stuff, presentation HTML and Javascript. The three have to work together to deliver the final solution. While you strive to avoid unnecessary dependencies with good design techniques and practices, you cannot avoid all dependencies, nor would even trying to avoid all possible dependencies be an efficient way to develop.
Example
There are coding practices that can make your code less sensitive to edits to the HTML and I consider those to be desirable practices. For example, consider this HTML snippet:
<div class="header">
<div class="headerBorder">
<div class="actions>
Hide
</div>
<div class="contentContainer">
<div class="content">
... content here
</div>
</div>
</div>
</div>
<div class="header">
... more of these repeated
</div>
And you want to have code that, when you click on the Hide link, it will hide the content.
If you code that like this:
$(".header .actions .hide").click(function() {
$(this).parent().next().children().first().hide();
});
Then, you have embedded in your Javascript some extremely detailed knowledge of the HTML structure in the area of your button and content and pretty much any structural change to that HTML (even just adding one more level of div to help with some layout) will break the Javascript. This is bad.
Instead, you could write this:
$(".header .actions .hide").click(function() {
$(this).closest(".header").find(".content").hide();
});
This depends only upon one HTML structural concept - that the .content that corresponds to the .hide button is somewhere in the common .header parent element. The entire structure within that .header parent can be changed and this code will not break. This is robust code that tries to be as independent of the details of the HTML structure as possible.
Anyway, what I want to learn today is what's the best way to target
the DOM from JS. Is it better to use IDs, class values or, data-*
attributes? How we can prettify a selector with plain English, etc...
It's best to use IDs to target elements for which there is only one unique element in the page.
It's best to use class names to target elements for which there can be more than one element in the page and you can combine that with other parts of a selector if you want to target only a specific item with a class name.
data attributes can be used in selectors, but that isn't really their primary purpose. I can't think of any reason why it would be better to use a data attribute instead of a class name. I use data attributes for storing actual data on an object that will be used by scripts. This tends to allow the code to be more generic and let the content describe itself.
When you talk about classes getting removed to change the state of the element, that is a legitimate use of a class, but it would just be a bad design decision to use the same class for selecting an element as for add/removing state. Use different class names for those two purposes. For example, you could have a class name called "selected" that indicates a selection state, but you would only use that in a selector if you wanted just the selected objects. If you wanted all line items in a table, you wouldn't use ".selected", you'd create a more descriptive class name for that object such as "lineitem". Remember, you can have multiple class names on an object so you can use different class names on the same object for different purposes.
You seem to be searching for some magic bullet here that prevents changes in the HTML from affecting Javascript in any way. That simply does not exist. Selecting a DOM element or finding a DOM element relative to something that was clicked will rely on some inherent knowledge of how the HTML is structured or tagged. What is important is that you minimize that dependence to only what is required and that anyone messing with the HTML has an understanding of how to best change things and not break the Javascript or discusses changes with someone who knows the Javascript. If you're using different skills/people on different portions of the project, they have to coordinate their efforts in order to not break things or be aware of what dependencies there are with the other parts of the system. That's just the way it is. There is no magic answer here that removes all dependencies between HTML and Javascript. Smart designs have smaller and more obvious dependencies. Poor designs have large and often hidden depedencies.
Your question about "plain English" isn't particularly clear to me. It seems obvious to use descriptive ID names, class names or attribute names that make it as obvious to the reader what that particular name is being used for. I'm not sure what you were looking for beyond that.
Related
I have a template that could be rendered multiple times within the same view.
The template contains a form and I have some jquery event listeners attached to the form elements using the html id.
For now I'm using 'g:set' to create an elementId variable at the top of the template using the current time in milliseconds and appending it to each element on the form. This way each form element will have a unique id within the page no matter how many times the same template is rendered.
My approach works but it seems to me that there must be a better way to achieve what I want to do?
Heres an example of my approach :
<g:set var="elementId" value="${'elementId-' + new Date().getTime()}" />
<form>
<g:textField id="${elementId}name" name="name"/>
<g:textField id="${elementId}address" name="address"/>
</form>
<script>
$("#${elementId}name").on("click", myFunction())
$("#${elementId}address").on("click", myFunction())
</script>
While it may feel a bit 'odd' or 'strange' to do this, your approach will accomplish what you are after. Adding in a random number or UUID that you generate at the GSP level too would help avoid collisions (though that may be overkill).
Grails doesn't offer any assistance in this manner per say. Since this is a concern of how elements are addressed in the browsers DOM and Grails typically addresses server-side concerns.
The alternative is to refactor your code to not rely upon element ids but rather something more generic and based on classification instead. Using class names would be a good approach. Depending on your requirements this may or may not work well.
Provided you have a container div with hundreds of very simple children elements such as the following:
<div id="stuffContainer" class="item-container">
<div class="single-item"></div>
<div class="single-item"></div>
<div class="single-item"></div>
<div class="single-item"></div>
<div class="single-item"></div>
<div class="single-item"></div>
[...]
</div>
Would including an unique id for each single element harm (client) performance in any (meaningful) way, be it rendering, javascript or memory wise?
Why I'm asking: I may need from time to time to reference specific items, and I'm trying to figure out whether I should precalculate in advance which items I will need to select, giving ids to them and leaving the rest out, or just assigning ids to all of them, which would make the process more straight forward but I wonder if this may be an overkill somehow.
Bonus points (if I could actually give them) if someone can talk about how this is handled by modern browsers and why it would/would not make a difference in terms of how browsers render and manage the DOM.
At the very most, I'm guessing that the basic few things a browser would do is assign the ID as a property to each element when building the DOM structure, as well as store the IDs in a hash table to facilitate things like #id selectors, document.getElementById() and idref lookups later. I don't think this is going to cause even a slight dent in observed performance or memory usage, as hash tables and the DOM are designed to be very well-optimized.
That said, if IDs aren't needed on your elements at all, then there quite simply is no point in assigning them IDs; you're going to end up with a whole lot of markup bloat instead. As Dan Davies Brackett mentions, that will obviously cause a slowdown since it depends on the client connection.
If you can afford to reference these elements using CSS selectors, you can always use :nth-child() to look up specific children. If you need to support older browsers, there's always a CSS2 solution. See these questions:
How can I get the second child using CSS?
How do I get the nth child of an element using CSS2 selectors?
As BoltClock implies, the answer to most performance questions is 'measure it!'. That said, you missed one potential axis for measurement: download size. Adding ID attributes to more elements than is necessary will add to your byte weight, not least because the elements are required to be unique (which means they won't zip as well as non-unique attributes might).
The original Q isn't very specific about contents/purpose and there should be variation, depending, IMO. I definitely disagree with the current accepted answer on one point. Looping through and attaching new IDs to a ton of HTML that's already rendered could cause massive amounts of reflow calculation which could get ugly depending on what 'stuffContainer' represents.
Build With IDs First From Server or Inject as Single Block on Client-Side if You Must
As a general rule, avoid hitting the DOM with changes repeatedly if you can avoid it. IDs built beforehand on the server is pretty negligible as far as the browser loading the page, IMO. Sure, it's a larger, and consequently slower hash-table but if we're talking hundreds and not tens of thousands I seriously doubt you're going to notice.
A more efficient client-side approach in the case of something like a select list built from data would be to build as a string first, with IDs and all, and then assign to innerHTML of a container or if like some of my js chat colleagues, you have a bizarre hang-up about innerHTML in every possible use-case even though it's in the spec now, at the very least build and append to a document fragment first. and then append that to your container.
Data-Attributes or Classes Over IDs
IMO, the smell-factor isn't so much about performance but rather HTML bloat and creating an ID dependency where none is needed, thereby blocking something else that might find a custom ID on one of your single-item divs useful. IDs are definitely the ideal way to narrow down an element look-up in JavaScript but in cases of containers with contents you'll get more flexibility out of ID'd containers than ID'ing every child item. The performance gain of one-stepping vs. two-stepping isn't worth the flexibility cost of applying generic IDs to elements.
As an alternative you can use classes with unique values or the data attribute, e.g. 'data-itemId="0"'. For smaller sets of HTML like a custom select list where IDs are connected to some server-side indexing system for ease of updating data I would tend to favor this highly visible approach as it makes it easier to understand the architecture, but it adds a lot of needless attributes to track in scenarios where hundreds to thousands of items might be involved.
Or Ideally (in most cases), Event Delegation
Most ideally, IMO, you avoid additional attributes altogether in cases where you only care about the child single-item element you're clicking and not what it's 'ID' is or the order those single-item containers will remain static and you can safely assume the positions are the effective IDs. Or another scenario where this might work with a non-static single-item set is if you've got single-item data in an array of objects that gets shuffled and then used to build and replace HTML on user-initiated sorts that will always tie order of the HTML to other data-tracking dependencies.
The non-Jquery approach (untested):
var myContainer = document.getElementById('stuffContainer');
//ignore following indent goof
myContainer.addEventListener('click', function(e){
var
singleItem,
elementOriginallyClicked = singleItem = e.target,
stuffContainer = this;
//anything clicked inside myContainer will trigger a click event on myContainer
//the original element clicked is e.target
//google 'event bubbling javascript' or 'event delegation javascript' for more info
//climb parentNodes until we get to a single-item node
//unless it's already single-item that was originally clicked
while( !singleItem.className.match(/[=\s'"]single-item[\s'"]/g) ){
singleItem = singleItem.parentNode;
}
//You now have a reference to the element you care about
//If you want the index:
//Get the singleItem's parent's childNodes collection and convert to array
//then use indexOf (MDN has normalizer for IE<=8) to get the index of the single-item
var childArray = Array.prototype.slice.apply(stuffContainer.childNodes,[0]),
thisIndex = childArray.indexOf(singleItem);
doSomethingWithIndex(thisIndex);
//or
//doSomethingWithDOMObject(singleItem);
} );
Or simple JQuery delegation style (also, untested):
$('#someContainer').on('click','.single-item', function(){
var $_singleItem = $(this), //jq handles the bubble to the interesting node for you
thisIndex = $_singleItem.index(); //also getting index relative to parent
doSomethingWithIndex(thisIndex);
//or
//doSomethingWithJQObject($_thisItem);
} );
There are no significant performance degradations from using id attributes, even when used hundreds of times. Although it would be slightly faster to hand-pick the elements you need to uniquely identify, in my opinion the performance improvement would not justify the extra time required to do so.
That being said, I'm not sure id attributes are even required in this case. If you were to use jQuery, you could select the fourth element, for example, using the following code:
$('.single-item').eq(3);
Using id's on everything would be a bit overkill in this case. I understand where you are coming from, but if you use a language like jQuery, selecting the children would be easy considering the structure. Here is an example of how you might know which one of the div's was clicked:
$('.single-item').click(function()
{
var yourClickedDiv = $(this);
// execute the rest of your code here
});
This is just a small example, but as you can see, you are able to access each div for whatever you need to do. This will keep the html file less cluttered from excessive id tags, along with keeping your file size a little bit smaller (not to mention save you the headache from generating every unique id).
As I've gotten deeper into using jQuery with various sites I've worked on, I've found that I can get lost on whether a class attribute value is appended to an element in the DOM in order to attach an actual CSS style, or to bind an event to it. As such, I've started leaning towards using the rel attribute on anchor tags to denote if something is going to be bound to an event, keeping the class attribute specifically for stylization. (I've not delved into this deep enough to determine if there are any drawbacks or fundamental flaws with this approach, however, and am open to comments & criticisms on it.)
It got me to thinking that others must have similar things they do to help keep their code organized, and I'm interested in learning about some new ideas that might be floating around out there.
Usually this is not much of an issue for me, even in medium sized projects.
I usually assign classes for styling, and I often end up using same selectors in JS code.
Semantically speaking, the rel attribute is not an appropriate way to store data. As it should point out the relation of a link to the target.
HTML5 makes things more flexible with data- custom attributes.
You use the class attribute when you have multiple HTML elements that have shared presentation or shared behavior.
So if you have several buttons for which you want to use the same event handler, then you give those buttons a class and then use JavaScript to select those elements (by class) in order to set the handler on them (you use a JavaScript library which has a selector engine). For example, in jQuery:
$(".addButton").click(function() {
// the event handler
});
Classes are used both for CSS styling and JavaScript manipulation.
Is there a way to create your own HTML element? I want to make a specially designed check box.
I imagine such a thing would be done in JavaScript. Something akin to document.createHTMLElement but the ability to design your own element (and tag).
No, there isn't.
The HTML elements are limited to what the browser will handle. That is to say, if you created a custom firefox plugin, and then had it handle your special tag, then you "could" do it, for varying interpretations of "doing it". A list of all elements for a particular version of HTML may be found here: http://www.w3.org/TR/html4/index/elements.html
Probably, however, you don't actually want to. If you want to "combine" several existing elements in such a way as they operate together, then you can do that very JavaScript. For example, if you'd like a checkbox to, when clicked, show a dropdown list somewhere, populated with various things, you may do that.
Perhaps you may like to elaborate on what you actually want to achieve, and we can help further.
Yes, you can create your own tags. You have to create a Schema and import it on your page, and write a JavaScript layer to convert your new tags into existing HTML tags.
An example is fbml (Facebook Markup Language), which includes a schema and a JavaScript layer that Facebook wrote. See this: Open Graph protocol.
Using it you can make a like button really easily:
<fb:like href="http://developers.facebook.com/" width="450" height="80"/>
The easiest way would be probably to write a plugin say in Jquery (or Dojo, MooTools, pick one).
In case of jQuery you can find some plugins here http://plugins.jquery.com/ and use them as a sample.
You need to write own doctype or/and use own namespace to do this.
http://msdn.microsoft.com/en-us/magazine/cc301515.aspx
No, there is not. Moreover it is not allowed in HTML5.
Take a look at Ample SDK JavaScript GUI library that enables any custom elements or event namespaces client-side (this way XUL for example was implemented there) without interferring with the rules of HTML5.
Take a look into for example how XUL scale element implemented: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/elements/scale.js and its default stylesheet: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/themes/default/input.css
It's a valid question, but I think the name of the game from the UI side is progressive markup. Build out valid w3 compliant tags and then style them appropriately with javascript (in my case Jquery or Dojo) and CSS. A well-written block of CSS can be reused over and over (my favorite case is Jquery UI with themeroller) and style nearly any element on the page with just a one or two-word addition to the class declaration.
Here's some good Jquery/Javascript/CSS solutions that are relatively simple:
http://www.filamentgroup.com/examples/customInput/
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
Here's the spec for the upcoming (and promising) JqueryUI update for form elements:http://wiki.jqueryui.com/Checkbox
If you needed to validate input, this is an easy way to get inline validation with a single class or id tag: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Ok, so my solution isn't a 10 character, one line solution. However, Jquery Code aside, each individual tag wouldn't be much more than:
<input type="checkbox" id="theid">
So, while there would be a medium chunk of Jquery code, the individual elements would be very small, which is important if you're repeating it 250 times (programmatically) as my last project required. It's easy to code, degrades well, validates well, and because progressive markup would be on the user's end, have virtually no cost on the server end.
My current project is in Symfony--not my choice--which uses complex, bulky server-side tags to render form elements, validate, do javascript onclick, style, etc. This seems like what you were asking for at first....and let me tell you, it's CLUNKY. One tag to call a link can be 10 lines of code long! After being forced to do it, I'm not a fan.
Hm. The first thought is that you could create your own element and do a transformation with XSLT to the valid HTML then.
With the emergence of the emerging W3 Web Components standard, specifically the Custom Elements spec, you can now create your own custom HTML elements and register them with the parser with the document.register() DOM method.
X-Tag is a helpful sugar library, developed by Mozilla, that makes it even easier to work with Web Components, have a look: X-Tags.org
A phenomena I'm seeing more and more of is Javascript code that is tied to a particular element on a particular page, rather than being tied to kinds of elements or UI patterns.
For example, say we had a couple of animated menus on a page:
<ul id="top-navigation">
...
</ul>
<!-- ... -->
<ul id="product-list">
...
</ul>
These two menus might exist on the same page or on different pages, and some pages mightn't have any menus.
I'll often see Javascript code like this (for these examples, I'm using jQuery):
$(document).ready(function() {
$('ul#top-navigation').dropdownMenu();
$('ul#product-selector').dropdownMenu();
});
Notice the problem?
The Javascript is tightly coupled to particular instances of a UI pattern rather than the UI pattern itself.
Now wouldn't it be so much simpler (and cleaner) to do this instead? -
$(document).ready(function() {
$('ul.dropdown-menu').dropdownMenu();
});
Then we can put the 'dropdown-menu' class on our lists like so:
<ul id="top-navigation" class="dropdown-menu">
...
</ul>
<!-- ... -->
<ul id="product-list" class="dropdown-menu">
...
</ul>
This way of doing things would have the following benefits:
Simpler Javascript - we only need to attach once to the class.
We avoid looking for specific instances that mightn't exist on a given page.
If we remove an element, we don't need to hunt through the Javascript to find the attach code for that element.
I believe techniques similar to this were pioneered by certain articles on alistapart.com.
I'm amazed these simple techniques still haven't gained widespread adoption, and I still see 'best-practice' code-samples and Javascript frameworks referring directly to UI instances rather than UI patterns.
Is there any reason for this? Is there some big disadvantage to the technique I just described that I'm unaware of?
First of all I agree with you that using the class approach is better, in general.
But I don't think I'd go so far as to say it's less coupling of the code to the UI. If you think about it, if the code assumes ID "foo" vs. class name "foo", you still have to know that when working with the UI. There's still a 'contract' between them -- whether you meet it through ID or class is not really different.
One disadvantage to using the class approach I'd imagine is speed -- it should be faster to find a particular element by ID than find potentially multiple elements by class. The difference is probably completely negligible though.
But, in the case where your code is designed to attach multiple behaviors, as in your two-dropdown example, using class certainly makes more sense. That is less coupling since your code is a bit more generalized, and your UI more likely to be customizable w/o changing the code.
One thing I'd change in both of your examples... why have the UL in the selector? If the code knows it can only possibly work if the target is a UL, well, that's one thing -- but in that case, it'd be better to avoid the UL in the selector and let the code throw a meaningful error if the target is found not to be a UL, lest the page just do nothing without any indication as to why (e.g. because the UI put the ID/class on a OL).
So in other words, just "#foo" or ".foo" not "ul.foo", etc.
I should point out that in case someone thinks the UL somehow makes the selector more efficient, it doesn't, since selectors are evaluated from right to left.
Your approach is preferred.
The reason people do things in different ways is because they can and it still works.