Adding Elements inside another DOM element in MooTools

Anurag picture Anurag · Jan 11, 2010 · Viewed 10.2k times · Source

Can I add an object of Elements inside another DOM element using grab or inject or anything else?

There are two items in the object, both of type Element that are created through Javascript:

var firstElem = new Element("div", {text: "something"}); // <div>something</div>
var secondElem = new Element("div", {text: "else"});     // <div>else</div>
var myDivs = new Elements([firstElem, secondElem]);

myDivs contains both the elements (firstElem, secondElem) as an array and I want to add this myDivs object to the DOM element below, using something like $("container").grab(myDivs). So the DOM state before adding looks like:

<div id="container"></div>

After adding, it looks like:

<div id="container">
    <div>something</div>
    <div>else</div>
</div>

But I'm getting this error when calling $("container").grab(myDivs):

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8

I could add each Element to the container one by one, but am wondering if there's a way to add an object of Elements directly due to the way my solution is architected.

Answer

Sampson picture Sampson · Jan 11, 2010

You ought to use .adopt() instead. See this example on jsBin: http://jsbin.com/anayu

window.addEvent("domready", function(){ 

  var firstElem  = new Element("div", {text: "something"}); 
  var secondElem = new Element("div", {text: "else"}); 
  var myDivs     = new Elements([firstElem, secondElem]); 

  $("container").adopt(myDivs); 

});