Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 520
streetparade Avatar asked May 21 '26 04:05

streetparade


2 Answers

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.

like image 125
Luca Matteis Avatar answered May 23 '26 16:05

Luca Matteis


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
});
like image 32
czarchaic Avatar answered May 23 '26 18:05

czarchaic