Reputation: 3097
When I use document.createElement javascript will add an element at bottom of body. How can I add an element in certain place ? (with document.createElement property, I mean store in a new variable)
Upvotes: 2
Views: 5640
Reputation: 625
You can add dom/Element at the start or at the end of any DOM element using jquery.
See the below example
<!-- HTML CODE -->
<div id="item">
this is only test
</div>
JQUERY Script:
$(document).ready(function(){
var item = "<span>New item</span>"
/* PrependTo */
$(item).prependTo('#item');
/* AppendTo */
$(item).appendTo('#item');
});
see the jquery documentation here and here
Upvotes: 1
Reputation: 22570
uhm, I could be wrong, but if your using jQuery, are you looking for something like:
var newDiv = $("<div />");
Also if you have a jQuery list of elements (an object array) like $(".divs")
which procs as [[Object Object], [Object Object]]
(whereas each [Object Object] is a div element containing class .divs
) you can add a new element to that list (without pasting to html body till ur rdy) by doing
$(".divs").add(newDiv);
Upvotes: 0
Reputation: 11536
When I use document.createElement javascript will add an element at bottom of body.
No, an element is returned, but it is not attached to anything. You need to do that yourself:
var ptag = document.createElement('p');
ptag.innerHTML = "hello world";
var someplace = document.getElementById('some_element_id');
someplace.appendChild(ptag);
That's plain js; the jquery techniques are terser.
Upvotes: 2
Reputation: 6463
<html>
<head>
</head>
<script type="text/javascript">
var my_div = null;
var newDiv = null;
function addElement()
{
newDiv = document.createElement("div");
newContent = document.createTextNode("test");
newDiv.appendChild(newContent);
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
</script>
<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
Upvotes: 2
Reputation: 51640
Just add the element as a child of another one.
For instance:
HTML
<body>
<div id="container"></div>
...
[page content here]
...
</body>
JS
newdiv = $("<div>something</div>");
$("#container").append(newdiv);
See the documentation of append
Upvotes: 0