169 points · by smanuel · 13y ago · 106 comments
If multiple elements of the same tag exist, a proper
array of elements is returned otherwise an Element is
returned.
STAHP. Please don't make the type of the return value dependent on runtime state. This is exactly why jQuery created its own array-like wrapper (which subclasses Array, fwiw).As far as APIs go, one way would just be to return a list always. The DOM, afaik, returns a special NodeList thing that isn't even an array. ( https://developer.mozilla.org/en-US/docs/Web/API/NodeList?re... ). What's the actual issue with using wrappers?
At root, the issue is that without widely available Proxy implementations (wildcard property intercept), wrappers must duplicate the entire underlying (and widely varying) API of the wrapped elements. You could do this by slavishly copying the DOM or by creating an entirely separate API (like jQuery).
Back when the DOM was a mess (3-4 years ago), the wrapper was the only sane approach (witness jQuery crushing Prototype). I'd argue things have changed: https://github.com/nbubna/mind-hacking/blob/gh-pages/extendi...
Returning a list for all operations is returning a wrapper, not the path i'm on. I would never argue that variable return types is ideal, but i currently prefer its problems to the problem introduced by using a wrapper API. :)
var allMyPageHeaders = HTML.find(".header");
allMyPageHeaders[0].textContent = 'This is my main header';
... and there's only one element on the page with the class ".header", my code is now broken.Unless I'm missing something, and an "HTML'ified node" acts as an array in the single case.
* Explain why someone should use it over the standard: jQuery
* Clearly explain the stance toward browser compatibility (not hand-waving & "oh who uses ie8 anyway?")
* Come up with something better than "It's smaller than jQuery!"
Without these points hit I don't even bother looking at DOM library. :/Edit: on the other hand, I feel like DOM traversal is becoming a smaller and smaller part of the JS I write. Maybe we'll find in five years that we don't need a DOM wrapper at all.
It only feels a bit more natural since the style it uses feels more direct...this is just another javascript wrapper for the DOM...a problem we (basically) solved with jQuery.
I also find myself rarely using jQuery for much these days when I use various MV* javascript libraries. This library looks neat, but I don't need to replace a library I use less and less...and has no real benefits other than size and API differences (that can basically be mapped to each other 1:1).
Yes, I could write one myself but this way I don't have to maintain the codebase. Nothing is a 'one size fits all' solution but for some this is a good start.
My point being don't dismiss it just because it doesn't fit your needs right now. It's still worth taking a look at.
Then why not just use Sizzle, which is jQuery's core selector engine without all the extra fluff? Again, the same question applies.
HTML.js is still smaller (a huge factor for me right now) and less 'robust', but that isn't always a bad thing.
The advantage of this approach is that if you decide you need more of jQuery (for example to support a plugin) you can pull in what you need rather than reinvent and debug your own.
https://rawgithub.com/nbubna/HTML/master/dist/HTML.min.js.gz
To those asking why you'd use this in place of jquery, the only reasons to use it are that it is smaller, vastly simpler, and yet does the things which many people use jquery for with a neat syntax. One of the main attractions for me is that it seems to get out of the way far more than jquery - elements aren't wrapped, behaviour is as you'd expect from the DOM, so you don't have to learn a new API just to manipulate objects in the way that you do with jquery.
Re speed issues, if you're using this enough or on documents where speed of selection is an issue, you could simply optimise the particular selector and just use the DOM to get a speed bump. I've not often seen a case in real-life where this matters though, does anyone have any examples we could look at?
If you want to use jquery plugins, cater for IE < 9, or use things like jquery animations or UI obviously you wouldn't want to switch.
1 - is there no equivalent for .closest()? Traversal from relative paths is kind of a big deal for a jQuery-like tool
2 - what is the type of `HTML.body.div`? HTMLDivElement or Array? If it depends on your markup, then that's a recipe for easy breakage
1 - you cannot be sure that return types will not change in the future (e.g. markup changes in maintenance phase), especially in large projects with lots of devs, hence my comment about brittleness.
2 - each() is verbose and encourages procedural style, which can cause redraw performance hits (i.e. someElements.readDOM().writeDOM() redraws much faster than someElements.each(function(el) {el.readDOM().writeDOM()}) since the browser's engine doesn't need to recalculate layout at every iteration
re: closest() - I've seen people do things like
$("li ul").closest("li").addClass("has-children")
for things like dynamic expandable tree initialization. Granted, it's not a very common use case though.2) elements.each('readDom').each('writeDom', 'value')
3) HTML.find('li ul').each('parentNode.classList.add', 'has-children')
EDIT: I should add—I am legitimately curious. I've only been learning plain JS for the last few months, and I'm wondering what pitfalls I might uncover.
(library this is forked from has documented performance hit: https://github.com/dunxrion/voyeur.js/issues/20)
Apart from the dot-traversal technique (both fixed and enhanced), everything is different in HTML (see the FAQ): each(), only(), extensibility, emmet abbreviations, and the upcoming event support.
This doesn't do everything jquery does, and is not intended as a drop-in replacement, more as a different way of doing things which is simpler, smaller and more intuitive.
https://github.com/inkling/backbone.native/blob/master/backb...
The $.ajax function was all I needed.
This seems like a pretty poetic way of describing differences between software packages. And I mean that in a non-charming way.
HTML.find('#empty li').only(function(el, i) {
return i % 2;
}).each('className','odd')
d3.selectAll("#empty li').filter(function(x,i) {
return i %2;
}).attr("class", "odd")DOM.body.div doesn't quite seem as nice to me.
In the end the author said "DOM extension is no longer to be feared". So what's the argument when you read the linked article? "Just choose non-conflicting name!" Really? That's your suggestion?
I like the idea if not so much the execution. It needs a partner for smoothing over event handling.
HTML is the root element (<html>), so it cannot be a function. HTML.ify() is only needed if you have a different library/interface that hands you an element, not retrieved via find() or dot-traversal.
zen-coding is designed for use in a text editor, though, and is a quick way of generating a ton of properly-indented, well-formed HTML.
A few (static) independent sections would do a much better job of promoting yourself.
HTML.find('body section .identity')
which is just like jquery's $('body section .identity')
and both depend on the structure of your document, so if the doc changes, the code must change. var $ = HTML.find.bind(HTML);
Enjoy. var $ = require('HTML');http://www.morearty.com/blog/2007/03/13/common-e4x-pitfalls/
5. E4X intentionally blurs the distinction between XML and XMLList
When you begin to learn E4X, you learn that there are two main data types, XML and XMLList. That seems simple enough. But then after a while, you start to notice places where it seems like the “wrong” type is being used, or where impossible things are happening.
var mydocument = <root> <rabbit name="Brownster Johansson McGee" /> </root>;
// 'mydocument.rabbit' means to get a list of ALL <rabbit> // nodes, so myPetRabbit must be an XMLList, right? But // I'll call my variable 'myPetRabbit', not 'myPetRabbits', // because I happen to know that I have only one pet // rabbit.
var myPetRabbit:XMLList = mydocument.rabbit;
// What's her name? Hey wait a minute, "her" name? // Why does this next line work? Isn't myPetRabbit an XMLList? // What does it mean to get an attribute of a list??
trace(myPetRabbit.@name);
The reason this works is that E4X intentionally blurs the distinction between XML and XMLList. Any XMLList that contains exactly one element can be treated as if it were an XML. (Furthermore, in this example, even if ‘myPetRabbit’ held a list of more than one node, myPetRabbit.@name is still a legal expression; it simply returns a list of all “name” attribute nodes of all of those elements.)
In fact, if you search the E4X spec (PDF) for “blur”, you will find 15 usages of the phrase “… intentionally blurs the distinction between….”
For example, another place where this blurring is evident is in the behavior of XMLList.toString(). As the Flex docs say:
If the XML object has simple content, toString() returns the string contents of the XML object with the following stripped out: the start tag, attributes, namespace declarations, and end tag.
If the XML object has complex content, toString() returns an XML encoded string representing the entire XML object, including the start tag, attributes, namespace declarations, and end tag.
So if an XMLList contains <node>hello</node>, then toString() will return "hello"; but if the list contains <node>hello</node><node>goodbye</node>, then toString() will return "<node>hello</node><node>goodbye</node>" (not "hellogoodbye"). Presumably this decision was made in an effort to achieve “do what I mean” behavior, where the output would match what developers most often intended; but personally I find it a little confusing. If you really need the full XML version of an XMLList that contains simple content, use toXMLString() instead of toString().
https://github.com/nbubna/HTML/tree/master/test
Looks like it passes on the latest FF and Safari, though I saw a couple of fails on the latest Chrome. Haven't tried IE, and it definitely won't work on older IE.
jQuery only lost 10% of its size on full builds when it eliminated IE6-8.
There is still plenty of stuff left to handle. Naive code that only handles common success case is of course going to be small. Even if the modern browsers didn't have bugs and behaved exactly the same, you would still have most of the stuff there.
jQuery features amazing event model with endless corner cases and optimizations* handled, powerful ajax library (Think of stuff like prefilters and transports) and so on.
* For example your typical delegation implementation traverses the propagation path over and over again for each handler, while probably not even checking for simple selectors.
"jQuery Core has more lines of fixes and patches for WebKit than any other browser." [1]
[1] http://blog.methvin.com/2013/02/tragedy-of-webkit-commons.ht...