Search code examples
javascriptmootools

mootools: Creating a new DOM element from an HTML


How to create DOM elements from string (pass from ajax) in Mootools?

In jQuery a simple solution is $( elements )

var elements = '<i>This is italic</i><b>this bold</b>...';

Solution

  • Without a string, you would use the Element class:

    var el = new Element('div#id.class', {
        text: 'My text',
    });
    

    With a string, you can check how it's one in Request.HTML, see here.

    var temp = new Element('div').set('html', response.html);
    response.tree = temp.childNodes;
    response.elements = temp.getElements(options.filter || '*');
    

    Basically Mootools elements & DOM elements are the same, this is another SO questions which creates DOM nodes from HTML: Creating a new DOM element from an HTML string using built-in DOM methods or prototype

    From old Mootools forums, I found an interesting idea too: add a new method Element.fromString() or String.toElement() which would contain this logic.