admin管理员组

文章数量:1253405

How can I create a div dynamically within a function, like this:

<div id="mydiv" class="notice" style="display:none;">
</div>

It would be very nice if I could create it also with jquery library.

How can I create a div dynamically within a function, like this:

<div id="mydiv" class="notice" style="display:none;">
</div>

It would be very nice if I could create it also with jquery library.

Share Improve this question edited Dec 26, 2009 at 2:19 Nadia Alramli 115k39 gold badges175 silver badges152 bronze badges asked Dec 25, 2009 at 20:40 streetparadestreetparade 32.9k39 gold badges105 silver badges123 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 15
var div = document.createElement("div");
div.setAttribute("id", "mydiv");

div.className = "notice";
div.style.display = "none";

// test case, append the div to the body
document.body.appendChild(div);

or with jQuery

$("<div id='mydiv' class='notice' style='display: none;'></div>").appendTo("body");

Be careful since in the jQuery approach an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.

Creating the element with jQuery will allow it to be referenced by variable name

var div=$(document.createElement('div'))
  .attr({id: 'myDiv'})
  .addClass('myNotice');

Now we can reference the div variable in the rest of our script.

//put it where you want
$('#someElement').append(div.hide());

//bind some events
div.mouseenter(function(){
  var offset=div.offset();
  //more code
});

Using just plain DOM:

var mydiv = document.createElement("div");
mydiv.setAttribute("id", "mydiv");
mydiv.setAttribute("class", "notice");
mydiv.setAttribute("style", "display:none;");
whateverContainer.appendChild(mydiv);

本文标签: jqueryCreate a div dynamically in JavascriptStack Overflow