Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a proof-of-concept implementation for getting jQuery itself work on objects. Through an object wrapper (<code>FakeNode</code>), you can trick jQuery into using its built-in selector engine (Sizzle) on plain JavaScript objects:</p> <pre><code>function FakeNode(obj, name, parent) { this.obj = obj; this.nodeName = name; this.nodeType = name ? 1 : 9; // element or document this.parentNode = parent; } FakeNode.prototype = { documentElement: { nodeName: "fake" }, getElementsByTagName: function (tagName) { var nodes = []; for (var p in this.obj) { var node = new FakeNode(this.obj[p], p, this); if (p === tagName) { nodes.push(node); } Array.prototype.push.apply(nodes, node.getElementsByTagName(tagName)); } return nodes; } }; function $$(sel, context) { return $(sel, new FakeNode(context)); } </code></pre> <p>And the usage would be:</p> <pre><code>var obj = { foo: 1, bar: 2, child: { baz: [ 3, 4, 5 ], bar: { bar: 3 } } }; function test(selector) { document.write("Selector: " + selector + "&lt;br&gt;"); $$(selector, obj).each(function () { document.write("- Found: " + this.obj + "&lt;br&gt;"); }); } test("child baz"); test("bar"); </code></pre> <p>Giving the output:</p> <pre> Selector: child baz - Found: 3,4,5 Selector: bar - Found: 2 - Found: [object Object] - Found: 3 </pre> <p>Of course, you'd have to implement a lot more than the above to support more complex selectors.</p> <p>BTW, have you seen <a href="http://www.hugoware.net/" rel="nofollow noreferrer">jLinq</a>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload