HTML.js – Befriend the DOM
nbubna.github.io
nbubna.github.io
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. :)
That state - that return value - does not behave like a DOM node. It doesn't quack like one. Sure, you can somehow create a mapping between the various scenarios - 0 results to null (or undefined?), 1 result to the result itself, and several to an array, but that just means that working with the result becomes harder.
As an API consumer of HTML.js as-is, I've got a few choices
- I can be hyperverbose and check all the time what the return value was (shudder)
- I can use a special-purpose api that happens to work in all cases. This is ok, but adds complexity, and since it's not enforced, I'm going to makes mistakes that will bite me confusingly at inopportune moments.
- I can make assumptions about the dom... this element must always be unique, right? and this selector always matches something, right? This coding style is hell to debug, especially without liberal asserts nor even the implicit asserts that a static type checker would make. This is the syntax the examples use, must be a great idea...
Let me put it this way: you're basically writing a query DSL, but you've chosen to make the syntax depend on the runtime state of the DOM. e.g. finding a link inside a div inside a section is written differently depending on whether there are several divs, or just one.
You say my dismissal of wrappers is entirely orthogonal because you are only comparing HTML.js to jQuery on jQuery's terms. jQuery made the choice to have syntax independent of the runtime state of the DOM. That's great, very useful!! I use jQuery all the time, it's not going away anytime soon. But with that benefit comes the cost of having to maintain a wrapper API, to learn a separate API with its own orthogonal set of drawbacks to using the DOM directly.
Web dev is changing. Single-focus libraries, web components, shadow DOM, all of these do not look fondly on wrapper APIs. Wrappers are essentially foreign tongues, not the native DOM they are designed to consume. HTML.js is designed for that world, where you are working with small, tightly controlled sections of native DOM.
If your page is the wild west with complex selectors and lots of interacting runtime changes, by all means, use a wrapper API like jQuery. But stop measuring every DOM helper with that stick. Sheesh.
And thank you for your anecdote, but i have never and will never stop doing something merely because some guy on the internet points out that some completely other person in a different context failed to pull it off.
How else can i spell this out... you do not need to worry about the distinction between nodes and node lists, if you just use each(). It's a proxy function that deals with the abstraction for you, just like jQuery's wrapper object does.
YOU. DO. NOT. NEED. AN. OBJECT. TO. HAVE. AN. ABSTRACTION.
Thank you and good night.
You shouldn’t return separate types of objects from a function based on the current state of the DOM, because the resulting code will be confusing, fragile, and hell to debug. To take the Clojure guys’ language, such code is “complex”. Don’t make APIs like that: it’s an anti-pattern. Either always return an array, or always return some kind of wrapper, or use separate methods for different return types, or use exceptions, or whatever mechanism you want, but pay close attention to cases where the typical API usage will lead to fragile code, and try to prioritize avoiding those.
I also, knowing that complexity was shifted to the return value, created an each() function that solves that problem entirely. It allows (even encourages) you to handle the result exactly like a proxy/wrapper. Again, how is that not related?
Yes, i am doing something unconventional, something that failed for others in the past. In fact, i'm doing several things like that. I'm also extending the DOM, not even using prototypes, but manually! Now, why don't ya'll explain to me all the conventional wisdom about those things too. I've gone against it, therefore i must be ignorant, right?
You mention .each, but the fact that you don't use it yourself in the primary HTML.js example should be telling you something: HTML.js does not encourage it's use. It's a cop-out; an escape valve that forces you into a less-than ideal syntax.
If you want to look at this through the lens of breaking with conventional wisdom you should be looking at why that convention arose in the first place.
Extending the DOM? You've got a good argument that the original reasoning no longer applies there! Conflating nodes and node-lists? What's different now that makes this a good idea?
Personally, if anything, I think the conflation is a worse idea now than it was a long time ago. Back when JS was "just" a small snippet in an otherwise static site making assumptions on the DOM of that site made some sense if it simplified your JS. Nowadays, the DOM is more and more an API for building an app, and less a static representation of a document. It's far from static, and depending unnecessarily on structural details of the DOM just means you need a more complicated (slower, more error-prone) mental model while programming.
It's not impossible - it's just making things hard for yourself. But what for? Where's the commensurate gain?
And i am most certainly NOT making things hard on myself. I forked Voyeur and rewrote it because the concept was so close to what i needed to make things much easier for working with the DOM. I needed a tight library that let me avoid branching code (unwieldy if/else) into either querySelector (node returned) and querySelectorAll (list returned). I wanted something that made it easy to traverse the short and usually quite static structures of my shadow DOMs or web components. The gains are numerous for me (and many others). It baffles me that you think using HTML.js is harder than straight DOM.
Now my lecture... You need to stop seeing the DOM as a large, dynamic structure of myriad, loosely defined nodes. The future of the web (what i'm aiming for) is components: groups of encapsulated structures whose internal relationships are well-defined and whose external relationships are nearly irrelevant. You probably won't understand the value of working close to the DOM with tiny libraries that don't abstract everything away for you until you pull your head out of 2010 design patterns and into 2015 ones.
Because querySelector and querySelectorAll is not the same function, it can return different things.
I don't know how this apply to your case where same dot traversal return different things.
If you want to use HTML.js's find() or dot-traversal, you must accept that your decision point was moved to how you handle the return value. And that you can use each() and only() to write code that safely abstracts the difference in results. Not an increase in complexity, just a shifting of it to somewhere i currently prefer.
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).
I still feel this library (with the exception of the cleaner feeling API) is not much more than a wrapper/extension around the native functionality.
But good job on making it pleasing to work with (as it appears to be), and the website around introducing it is also quite nice...if I was using these DOM-wrapper-sugarizing libs to any serious degree these days I would likely consider it.
Overall this looks nice, but I feel like the javascript world is mostly moving away from the whole 'modify the layout that is pre-generated' and more towards a data driven/render what I specify world...
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 seems like a pretty poetic way of describing differences between software packages. And I mean that in a non-charming way.
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.
but part of the reason they are so prolific is that they focus on very small, single use modules that do one thing well. So they have hundreds of repos, but many of them are 10 - 15 lines of code.
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().
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...
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.