0

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); 

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you don't need to wrap the DOM object with jQuery inside append. could just do $("#SomeOtherDiv").append(myFancyDiv)
1

This should do it !

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

Comments

1

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

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

Comments

0

This will work in jQuery 1.4

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

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

Comments

0

You can try this way:

$("<div/>", {

  // PROPERTIES HERE

  text: "Click me",

  id: "example",

  "class": "myDiv",      // ('class' is still better in quotes)

  css: {           
     color: "red",
     fontSize: "3em",
     cursor: "pointer"
  },

  on: {
    mouseenter: function() {
      console.log("PLEASE... "+ $(this).text());
    },
    click: function() {
      console.log("Hy! My ID is: "+ this.id);
    }
  },

  append: "<i>!!</i>",

  appendTo: "body"      // Finally, append to any selector

}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.