streetparade
streetparade

Reputation: 32888

Create a div dynamically in Javascript

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.

Upvotes: 2

Views: 12832

Answers (3)

czarchaic
czarchaic

Reputation: 6318

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

Upvotes: 2

Kevin Reid
Kevin Reid

Reputation: 43773

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

Upvotes: -1

Luca Matteis
Luca Matteis

Reputation: 29267

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.

Upvotes: 15

Related Questions