jQuery添加DOM元素

问题描述 投票:0回答:5

这可能是一个简单的答案,但我正在尝试将一个dom创建的元素(即document.createElement(...))添加到jQuery Selector。

jQuery有很多用于添加html的功能

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

但我想要做的是添加一个dom OBJECT

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

// This is the theoretical function im looking for.
$("#SomeOtherDiv").htmlDom(myFancyDiv); 
javascript jquery dom
5个回答
3
投票

试试这个:

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

在$(...)中包装DOM元素,我希望你可以使用任何带有jQuery元素集合的jQuery DOM操作函数来添加它。


1
投票

这应该做到!

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

1
投票

你可以通过简单地删除jQuery来简化和加快操作:

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

0
投票

这将适用于jQuery 1.4

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

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


0
投票

你可以这样试试:

$("<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

}); 
© www.soinside.com 2019 - 2024. All rights reserved.