Using JavaScript create a div and also it will come top of the main div
This is my HTML template.
<div id='main'>
<div id='1'>one</div>
</div>
I want dynamically create a new div with inside of main div and also it (new div>) will come to top 开发者_如何学JAVAof the main div. The answer look likes
<div id='main'>
<div id='new'>new</div>
<div id='1'>one</div>
</div>
How can this be achieved?
You can use jQuery's .prepend()
method when selecting the #main
element.
$('#main').prepend('<div id="new">new</div>');
You should note that it is not valid HTML4 to have an ID that starts with a number. So id="1"
wouldn't be valid.
Changing it to a valid id like id="div_1"
, you could select that and use jQuery's .before()
method instead.
$('#div_1').before('<div id="new">new</div>');
And in either case, remember to wrap your jQuery code like this so that it doesn't run until the DOM is ready.
$(function() {
$('#main').prepend('<div id="new">new</div>');
});
精彩评论