views:

73

answers:

4

This may be a simple answer, but I'm trying to add a dom-created element (i.e. document.createElement(...)) to a jQuery Selector.

jQuery has a great assortment of functions for adding html

  • .html(htmlString)
  • .append(htmlString)
  • .prepend(htmlString)

But what i want to do is add a dom OBJECT

var myFancyDiv = document.createElement("div");
myFancyDiv.setAttribute("id", "FancyDiv");

// This is the theoretical function im looking for.
$("#SomeOtherDiv").htmlDom(myFancyDiv); 
+3  A: 

Try this:

$("#SomeOtherDiv").append($(myFancyDiv)); 

Wrapping the DOM element in $(...), I'd expect you could add it with any of the jQuery DOM manipulation functions that take a jQuery element collection.

Frank Schwieterman
you don't need to wrap the DOM object with jQuery inside append. could just do `$("#SomeOtherDiv").append(myFancyDiv)`
Anurag
+1  A: 

This should do it !

  $("#SomeOtherDiv").append('<div id="FancyDiv"></div>')); 
mcgrailm
A: 

This will work in jQuery 1.4

$("<div/>",{
    id: 'FancyDiv'
}).appendTo("#SomeOtherDiv");

http://api.jquery.com/jQuery/#jQuery2

RedWolves
A: 

You could make things simpler and faster by cutting out jQuery entirely for something this simple:

document.getElementById("SomeOtherDiv").appendChild(fancyDiv);
Tim Down