views:

307

answers:

3

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.

+6  A: 
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.

Luca Matteis
the jquery function works but it inserts at the and of the body
streetparade
that's because my testcase has the "appendTo" at the end. remove that and use it as you see it fit.
Luca Matteis
even if i remove document.body.appendChild(div);it realy doesnt work,
streetparade
yeah thanks i solvet it
streetparade
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.
J-P
A: 

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);
Kevin Reid
no, for CSS classes you need to use the className attribute.
Luca Matteis
`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.
bobince
Huh. I thought the property shortcuts were browser-invented stuff that never got into any DOM specification. I see [I am wrong](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html). Thanks, bobince.
Kevin Reid
+1  A: 

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