2

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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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

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

Comments

-1

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

2 Comments

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.
Huh. I thought the property shortcuts were browser-invented stuff that never got into any DOM specification. I see I am wrong. Thanks, bobince.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.