How do I add a div to a page using javascript? - javascript

So... I want to add the following right before the /body of a document, I can't seem to find a way to make it work:
document.body.innerHTML+="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\"");

Especially with the <body> element, you shouldn't be using innerHTML to append elements to an element. An easier way is with DOM methods like createElement, insertBefore or appendChild.
https://developer.mozilla.org/en-US/docs/DOM/document.createElement
https://developer.mozilla.org/en-US/docs/DOM/Node.insertBefore
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
Try this:
var div = document.createElement("div");
div.style.position = "absolute";
div.style.right = "-10px";
div.style.bottom = "10px";
div.innerHTML = "response";
var lastChild = document.body.lastChild;
document.body.insertBefore(div, lastChild.nextSibling);
Although I guess it would make sense to just append it to the body:
document.body.appendChild(div);
(instead of the last two lines in my first example)
It also depends on when you're calling this code. Of course it will work if executed in the middle of the <body>, but you probably want to wait until the body (DOM) is ready so that the element is actually appended at the real end of the body. By using something like:
window.onload = function () {
// Your code from above
};
This will make sure the original <body> contents are ready.

Don't add stuff like that! Instead, do this:
var newDiv = document.createElement('div')
newDiv.style.position = 'absolute'
newDiv.id = 'myDiv'
newDiv.innerHTML = 'hello'
//etc.
document.body.appendChild(newDiv)

Change code to
document.body.innerHTML="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\"";
Remove ) at the end

What about:
var div = document.createElement("div");
// it's better use a CSS here instead
div.style.position = "absolute";
div.style.right = "-10px";
div.style.bottom = "10px";
div.innerHTML = "response";
document.body.appendChild(div);
?

Related

Javascript div doesn't work

var udiv = document.createElement('div');
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
div.appendChild(udiv);
I've been trying to get this to work, but when I open the page there's nothing there. I know the Javascript file works because everything else shows up, but the div doesn't. There's no error.
But both are new elements, Append those elements to an already existing element or to the body,
.
.
.
div.appendChild(udiv);
document.body.appendChild(div)
You've appended udiv to div, but you've never appended div to the DOM.
You didn't append the div object to the DOM
document.body.appendChild(div);

Adding div dynamically using href link

I'm trying to add a div dynamically using an link and some javascript. I've set up a jsfiddle http://jsfiddle.net/W4Sup/1654/.
Here's the html
Add Div
Here's the css
div {
border: 1px dotted red;
padding: 10px;
}
And here is the javascript:
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = "I'm the first div";
// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';
// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);
innerDiv.innerHTML = "I'm the inner div";
function addDiv() {
var newDiv = document.createElement('div');
newDiv.className = 'block-3';
iDiv.appendChild(newDiv);
newDiv.innerHTML = "Another inner div";
}
Can someone explain what I've got wrong please
check this updated fiddle, basically addDiv was not visible to the click event handler since it was not in a global scope (since it is inside domready event handler)
<script>
var addDiv;
</script>
addDiv = function addDiv() {
var newDiv = document.createElement('div');
newDiv.className = 'block-3';
iDiv.appendChild(newDiv);
newDiv.innerHTML = "Another inner div";
return false;
}
Well first of all you dont need the href, only the onclick will matter, thus making it usable on any html tag, not only <a>'s
Add Div
the onclick doesnt take a ; at the end of your function, it's an assignation, you'not calling it
I prefer the assign-in-the-JS approach. Set your event listener in your JS by grabbing that link and putting addDiv in its click event handler.
Demo using your code
Basic changes -
JS:
document.getElementById("joe").addEventListener("click", addDiv, false);
...
function addDiv( event ) {
event.preventDefault();
...
}
HTML:
Add Div
You don't have to use an ID, it was just the most convenient way in this example. I recommend it though if that's an option for you.

create div for each createelement, javascript

How to create div in javascript for each create elements(DOM) and retrieve their values?
for (i = 1; i <= 3; i++) {
var input = document.createElement('input');
input.setAttribute("id", "x" + i);
var div = document.createElement('div');
div.id = "div"+i;}
I'm assuming you want to append all of your inputs into your divs and then your divs into the body.
Use the function appendChild, which is available on all DOM nodes, furthermore, your code will not work since inputVN is undefined.
you can try with this
document.body.appendChild(element);
example for create a div with javascript
var Div = document.createElement('div');
Div.id = 'DivId';
document.body.appendChild(Div);
this is a little example how create a div, you can try with these

How can I implement prepend and append with regular JavaScript?

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

Wrapping a div around the document body contents

I am trying to dynamically wrap the contents of a document's body tag in a DIV. So far, I have used the following code:
document.body.innerHTML = '<div id="wrap">' + document.body.innerHTML + '</div>';
This works, but has the unwanted side effect that other scripts on the same page stop working (I assume because changing innerHTML renders any object references they may have held useless).
What would be the best/most efficient way to achieve this and keep the references intact, using pure JavaScript, or the Prototype framework?
You would do something like:
var div = document.createElement("div");
div.id = "wrap";
// Move the body's children into this wrapper
while (document.body.firstChild)
{
div.appendChild(document.body.firstChild);
}
// Append the wrapper to the body
document.body.appendChild(div);
you could try this? (untested)
var newDiv = document.createElement('div')
newDiv.setAttribute('id','wrap');
var bodyChildren = document.body.childNodes;
for(var i=0;i<bodyChildren.length;i++){
newDiv.append(bodyChildren[i]);
}
document.body.appendChild(newDiv);
Not sure about prototype, but in jQuery you can do this
$('body').wrap('<div id="wrap"></div>');
Maybe something like this:
var body = document.body;
var div = document.createElement('div');
div.className = 'wrapper';
div.innerHTML = body.innerHTML;
body.innerHTML = div.outerHTML;
$('#iframe').contents().find('body').wrap('<div class=body></div>');
$('#iframe').contents().find('body').replaceWith(function() {return this.innerHTML});
$('#iframe').contents().find('.body').wrap('<body></body>');
this lines are going to wrap a div inside body element tag. First, it will wrap the body tag, then remove the body tag and append its all contents to the body div and the 3rd line will wrap this div again with the body tag.

Categories

Resources