having fun with code

Creating HTML blocks with Mootools

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:

  1. var element = jQuery('<div id="foo">bar</div>');

In Mootools, the equivalent should be:

  1. 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:

  1. String.implement({
  2.  toElement: function() {
  3.    return new Element('div', {html:this}).getFirst();
  4.  }
  5. });

Now you can do this:

  1. var element  = '<div id="foo">bar</div>'.toElement();

To try it, paste this snippet on Firebug’s console:

  1. String.implement({
  2.  toElement: function() {
  3.    return new Element('div', {html:this}).getFirst();
  4.  }
  5. });
  6. 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 :)

Related Posts:

3 Comments to Creating HTML blocks with Mootools

  1. September 3, 2009 at 09:50 | Permalink

    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

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info