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.
Nadia Alramli
116k39 gold badges176 silver badges152 bronze badges
asked Dec 25, 2009 at 20:40
streetparade
33.1k39 gold badges106 silver badges123 bronze badges
3 Answers 3
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.
answered Dec 25, 2009 at 20:42
Luca Matteis
29.3k22 gold badges118 silver badges172 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
streetparade
the jquery function works but it inserts at the and of the body
Luca Matteis
that's because my testcase has the "appendTo" at the end. remove that and use it as you see it fit.
streetparade
even if i remove document.body.appendChild(div); it realy doesnt work,
James
jQuery does not use innerHTML to append to the
"body". It creates the DOM element from the HTML provided by using an off-DOM innerHTML trick plus a document fragment -- to actually add the resulting DOM node to the document, jQuery uses regular DOM methods, like element.appendChild etc.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
});
answered Dec 25, 2009 at 21:10
czarchaic
6,34833 silver badges24 bronze badges
Comments
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);
answered Dec 25, 2009 at 20:51
Kevin Reid
46.1k14 gold badges100 silver badges127 bronze badges
2 Comments
bobince
setAttribute ('class', '...') is correct, but doesn't work in IE pre-v8 because IE doesn't know the difference between an attribute (class) and a property (className). You should always use DOM Level 1 HTML properties (mydiv.id= 'hidden'; mydiv.className= 'notice'; mydiv.style.display= 'none') in preference to setAttribute partly due to these IE bugs and partly because the property way is much simpler and easier to read.Kevin Reid
Huh. I thought the property shortcuts were browser-invented stuff that never got into any DOM specification. I see I am wrong. Thanks, bobince.
default