Appending a div element using javascript - javascript

I am new to jQuery and I am practicing appending div elements. Here is my code:
<!doctype html>
<html lang="en">
<head>
<title>Div Id</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<script>
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is a first division");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
</script>
<body>
<div id="div1">This is a second division.</div>
</body>
</html>
Output would be:
This is a second division.
But as per my implementation the output should be
This is a first division
This is a second division.
I am not able to figure where it is going wrong. Please someone help me out with this.
Thanks in advance.

onload is a property of the window object, not the document.body object.
This works:
window.onload = addElement;

actually it works.... try to move your javascript in the head of you html file
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is a first division");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
<div id="div1">This is a second division.</div>

$('#div1').before('<div id=div0>This is a first division</div>')
demo
If you want Jquery it is as simple as this.

If you want to use jQuery you can check this fiddle:
$('body').prepend('<div>This is a first division</div>');

Related

Why aren't the child nodes of this paragraph attribute being displayed?

I am new to JavaScript, and I was putting some code on an editor to test it out.
I am trying to dynamically create elements by appending child nodes to a "p" attribute, but I am not seeing these child nodes displayed. Could you please explain why, and how I can make all of the nodes to be displayed?
Here is the code:
<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() {
var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode);
document.getElementById("firstP").appendChild(newP);
}
</script> </head>
<body> <p id="firstP">firstP<p> </body>
</html>
Here is the output: firstP
I was expecting to get:
firstP
p
This is a new text node
UPDATE: I accepted the answer that worked. Also realized that I was supposed to expect the output to be:
firstP
This is a new text node
You made typo error and child node need to be added to a p parent tag, so inserting the p tags into a div tag is better, also call the addNode function, this will work ;-)
<html>
<head>
<title>t1</title>
</head>
<body>
<div id="firstPContainer">
<p>firstP</p>
</div>
<script type="text/javascript">
function addNode() {
var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode);
document.getElementById("firstPContainer").appendChild(newP);
}
addNode();
</script>
</body>
</html>

appendChild is not a function - what am I doing wrong?

I know this is a very common error, but I just can't figure out why this isn't working.
I want to change the value of a span dynamically. Simple, right? I've tried $span.innerHTML = "text" and $span.innerText = "text", which do nothing, but don't throw any errors. My most recent attempt looks like this:
var $resourceSpan = $("#divname"+dynamic_variable);
var stringVar = functionThatReturnsString();
while( $resourceSpan.firstChild ) {
$resourceSpan.removeChild( $resourceSpan.firstChild );
}
var textNode = document.createTextNode(stringVar);
$resourceSpan.appendChild( textNode );
Does anyone know why I'm throwing this error? Thanks
You are dealing with jQuery object, methods like removeChild() and appendChild() belongs to dom element not to the jQuery object.
To remove all contents of an element you can use .empty() and to set the text content of an element you can use .text(), but using .text() will replace existing content so in your case you can just use
var $resourceSpan = $("#divname" + dynamic_variable);
var stringVar = functionThatReturnsString();
$resourceSpan.text(stringVar);
Did you wanna do somethin like this?
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>HI, IM SOME TEXT</span>
<input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... -->
<script>
var text = 'I AM THE NEW TEXT'; // The text to go in the span element
function changeText(){
var span = document.querySelector('span');
span.innerHTML = text;
}
</script>
</body>
</html>

create div horizontal layout element dynamically with javascript

How can I create <div horizontal layout></div> element dynamically using javascript?
i can create div element with document.createElement("div"); but how do I add horizontal layout to it?
<html>
<head>
<script type="text/javascript">
window.onload = function() {
newdiv = document.createElement("div");
newdiv.setAttribute('horizontal', '');
newdiv.setAttribute('layout', '');
document.body.appendChild(newdiv);
// You can insertBefore() too.
// Or... document.body.innerHTML = document.body.innerHTML + '<div horizontal layout></div>';
}
</script>
</head>
<body>
</body>
</html>
Some helpful links:
http://www.w3schools.com/jsref/met_document_createelement.asp
Adding elements to the DOM
Searching elements in DOM
How to add or update an attribute to an HTML element using JavaScript?
And so on.

add element in certain place

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

JavaScript Getting ID of A Div

I have a div box with its id and an textarea.
When I click on my div box I should get div ID through Javascript and get it printed on the textarea. I have tried but its not working. when I click the text area it says "undefined". Kindly help me.
Here is the code:
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
getElementsByTagName returns a nodeList of DOM nodes, which acts like an array.
You'll need to select the first item in the node list before you can access the node's ID:
textEl.value = divEls[0].id;
Alternatively, you could have passed this to get_id():
function get_id(node) {
var textEl = document.getElementById('mytextarea');
textEl.value = node.id;
}
onclick="get_id(this)"
But honestly, all of the JavaScript should be external to your HTML file. HTML belongs in .html files, CSS belongs in .css files and JS belongs in .js files.
//i haven't checked this code, and you probably want to modify it to be more generic.
window.onload = function () {
var myDiv, myTextArea;
myDiv = document.getElementById('mydiv');
myTextArea = document.getElementById('mytextarea');
myDiv.onclick = function () {
myTextArea.value = myDiv.id;
};
};
Rewrite your code as below:
<html>
<head>
<script type="text/javascript">
function get_id(element) {
var textEl = document.getElementById("mytextarea");
textEl.value = element.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id(this)" style='border-width: 1px; border-color: #C0C0C0;
border-style: solid; background-color: #C0C0C0; width: 130px; height: 10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
When you use getElementsByTagName, you get ALL of the elements with that tag as an array.
If you want the first DIV then you need to add [0] this way:
var divEls = document.getElementsByTagName("div")[0];
The remaining code is ok.
getElementsByTagName returns an array even if it contains only one object. You should access it like this:
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls[0].id;
}
divels is, as the plural is indicating, an Array (correct: a NodeList), which has no id property. Its items have, so eg. textEl.value=divEls[0].id; will work (if the List is empty, this will throw an error).
try this function
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.item(0).id;
}
Ok I figured it out. document.getElementsByTagName("div") will return all the elements which have tag name div as an array of nodes. Here in your code there is only one div element hence first element is div itself. As in an array first element has number index = 0 so we can get first by document.getElementsByTagName("div")[0] or in your code divEls[0], and then we can get its id by simply getting divEls[0].id. Now as we have got the div id we can set the value of text area equal to this div id as: textEl.value = divEls[0].id Here is your code with changes. Hope this Helps
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
/*get the first item in the nodelist ie divEls[0] = document.getElementsByTagName("div")[0] and then get its id by
its id by divEls[0] */
textEl.value = divEls[0].id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>

Categories

Resources