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)
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)
Share Improve this question edited Apr 24, 2012 at 14:26 nico 51.8k17 gold badges91 silver badges118 bronze badges asked Apr 24, 2012 at 14:19 MajAfyMajAfy 3,09712 gold badges50 silver badges83 bronze badges 1-
document.createElement
does not add the element anywhere by itself, you have misunderstood. – Esailija Commented Apr 24, 2012 at 14:22
5 Answers
Reset to default 2<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>
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.
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
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
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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744293581a4567151.html
评论列表(0条)