Sometimes we need to create HTML from JS. There are multiple ways to do this, from using innerHTML to creating element by element appending child to parents, setting attributes, etc. And there are as many different opinions about what is the right way to do it.
Meanwhile, once thing I missed from jQuery, not available on Mootools, was the ability to do something like this:
-
var element = jQuery('<div id="foo">bar</div>');
In Mootools, the equivalent should be:
-
var element = new Element('<div id="foo">bar</div>');
But that does not work.
On the Mootools mailing list, someone was asking about how to implement this and we just found a different approach, which instead of using the Element class, extends the String class like this:
-
String.implement({
-
toElement: function() {
-
return new Element('div', {html:this}).getFirst();
-
}
-
});
Now you can do this:
-
var element = '<div id="foo">bar</div>'.toElement();
To try it, paste this snippet on Firebug’s console:
-
String.implement({
-
toElement: function() {
-
return new Element('div', {html:this}).getFirst();
-
}
-
});
-
console.log('<div id="foo">bar</div>'.toElement().get('id'));
Nice, uh? Of course, the HTML can be as complex as you need and where do you get the content of the string is up to you :)
There’s actually a solution for you coming in the next MooTools More (hopefully coming out in a week or so):
http://github.com/mootools/mootools-more/blob/master/Source/Element/Elements.From.js
There are a few things to recognize here:
1) a string of html may return more than one element at the top level, so it’s better to return an instance of Elements instead of Element
2) attempting this with table elements will produce poor results
3) if your html includes scripts, you might want to handle that differently
Thanks for the tip Aaron. We noticed here the problem with multiple root elements on the html fragment. Our solution was to return .getChildren() instead of .getFirst(), but that wouldn’t work either if there were any text nodes at the root of the html (kinda weird but..). Maybe you would like to consider that on the new Elements.From code.
What is exactly the issue with table nodes and what do they require special handling?
Finally, the best way to generate HTML from Javascript: Mooml :)
http://mootools.net/forge/p/mooml