I have been experimenting with templating in js and have come across a pretty cool problem. Say you have a handlebars template. Then compile it and output it
var template =
'<h1>Hello</h1>' +
'<ul>' +
'<li>{{name}}</li>' +
'<li>{{address}}</li>' +
'<li>{{phone}}</li>' +
'</ul>';
var html = Handbars.compile(template)(
{name: 'Austin', address: '42nd St.' phone: '(123) 456-7890'}
);
// Results in
console.log(html);
=> <h1>Hello</h1>
<ul>
<li>Austin</li>
<li>42nd St.</li>
<li>(123) 456-7890</li>
</ul>
Now say you want to make that a jQuery object and act on it maybe find the ul
var $html = $(html)
var x = $html.find('ul'); \\ Or
var y = $('ul', $html)
console.log(x);
=> []
conosle.log(y);
=>
console.log($html)
=> [<h1>Hello</h1>, <ul>...</ul>]
What this shows is when you jQueryify a string without a root node you get an array of nodes
and the finds only act on $html[0]
The only way I have been able to solve this is to include a root node in my templates but I don’t like adding pointless non-semantic markup just because jQuery will not act nice.
How can you solve this programmatically instead of modifying markup.
In fact,
.finddoes operate on both elements of the jQuery object, but it onlyfinds their descendants. What you want is.filter: