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 badges3 Answers
Reset to default 15var 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
版权声明:本文标题:jquery - Create a div dynamically in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740762946a2282271.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论