Wrapping a div around the document body contents - javascript

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.

Related

javascript create div and append it next to a child element without id

Using the solution suggested here: https://stackoverflow.com/a/32135318/10279127 i'm trying to create a new div, and append it inside a parent div with id, next to a child <a> html element.
html:
<div id="div0">
anchor text
// I'd like to place the new div here
</div>
js:
Element.prototype.appendAfter = function(element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
var NewElement = document.createElement('div');
NewElement.id = 'newDivID';
var tToAfter = $('#div' + index + ' > a'); // this is what i tried but doesn't work
NewElement.appendAfter(tToAfter);
If inside .appendAfter(...) instead of tToAfter i write document.getElementById('randomElementId') it works and appends it, so i think must be pure javascript, is there a way in js to do something like: document.getElementById('div' + index).firstChild to get the <a> ?
Or to make it entirely with jQuery using the insertAfter (https://stackoverflow.com/a/8707793/10279127) ?
you can select inside div#div0 by using
const anchor = document.querySelector("#div0>a");
You can simplify your approach by using insertAdjacentElement. For example (the css is irrelevant - just there so you can visually see the inserted div):
const anchor = document.querySelector('#div0 a');
const elem = document.createElement('div');
elem.id = 'newDivID';
anchor.insertAdjacentElement('afterend', elem);
div:not(#div0) {
height: 20px;
background-color: green;
}
<div id="div0">
anchor text
// I'd like to place the new div here
</div>

InnerHTML does not include the "frame" tag

I have a DOM element, which inside it has a node with the tag "frame".
But when I do innerHTML, the "frame" tag disappears. Why?
Example:
I have this string:
<div><p>Text</p><frame></frame></div>
If I want to put this string as the HTML of an element, the "frame" tag disappears:
var div = document.createElement('div');
div.innerHTML = str.trim();
Result:
<div><p>Text</p></div>
How can I resolve this?
You can't use <frame> inside <body> tag.
For that, write <frameset> instead of <body> and use <frame> inside <frameset></frameset>.
And, in the <body> tag( or DOM), you can use <iframe>.
Try this
var container = document.createElement('div');
var div = document.createElement('div');
var p=document.createElement('p');
p.innerHTML="Text";
var frame=document.createElement('frame');
div.appendChild(p);
div.appendChild(frame);
container.appendChild(div);
alert(container.innerHTML);
document.getElementById("mainContainer").appendChild(container);
alert(document.getElementById("mainContainer").innerHTML);
<div id="mainContainer"></div>

Changing JavaScript into jQuery - createElement

I'm trying to use the draggable and resizable jQuery function, but I may have to change a little bit of this code to jQuery.
I have this HTML code:
<div id="resizable2" class="ui-widget-content">
<h3 class="ui-widget-header">MS</h3>
</div>
This works great with the jQuery:
$(function() {
$( "#resizable" ).draggable();
$( "#resizable" ).resizable();
}
But then, I've tried to use it with a div created by javascript:
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
document.body.appendChild(newDiv);
newDiv.appendChild(h);
newDiv.className = "ui-widget-content";
h.appendChild(text);
h.className = "ui-widget-header";
newDiv.id = "resizable";
}
And it's not working
Change your dom object to a jQuery object by calling $(newdiv) and re-initialise the resizable and draggable functionality on the new content.
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
newDiv.appendChild(h);
newDiv.className = "ui-widget-content";
h.appendChild(text);
h.className = "ui-widget-header";
newDiv.id = "resizable";
$(newDiv).resizable(); //Add this
$(newDiv).draggable(); //and this
document.body.appendChild(newDiv); //Append to the dom once you've finished with it.
}
As devqon has mentioned, the reason for this is that this function adds dynamic content (content which isn't there on page load) this means that the draggable and resizable functionality is not present on this new content. This is why you need to re-initialise the connection between the new element and the functionality.
Also as menioned don't re-use ID's, they must be unique. It is bad practice to use the same id for multiple elements and will very likely lead to other issues.
Lastly, it is a good idea when creating new content to manipulate it first and add it to the page at the end. In this instance you are appending further content inside the newly created div. I would do this first and then when finished with it, add it to the page.
Hi I have changed your function to:
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
newDiv.id = "resizable";
newDiv.className = "ui-widget-content";
h.className = "ui-widget-header";
h.appendChild(text);
newDiv.appendChild(h);
document.body.appendChild(newDiv);
}
And I have created a jsfiddle for you to try yourself:
http://jsfiddle.net/ttw7218z/4/
Well you need to initialize resiazble plugin on new DOM elements. You already have a few JS solutions so I will post one more version using jQuery for elements creation:
function addnewbox() {
$('<div class="ui-widget-content resizable">' +
'<h3 class="ui-widget-header">MS</h3>' +
'</div>').appendTo('body').resizable();
}
One more thin you should be aware of: you should not duplicate ids, they must be unique. So instead of multiple #resizable use .resizable classes.

How do I add a div to a page using 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);
?

Adding div element to body or document in JavaScript

I am creating a light box in pure JavaScript. For that I am making an overlay. I want to add this overlay to body but I also want to keep the content on the page. My current code adds the overlay div but it also removes the current contents in body. How to add div element and keep contents on body?
var el = document.getElementById('element');
var body = document.getElementsByTagName('body');
el.innerHTML = '<p><a id="clickme" href="#">Click me</a></p>';
document.getElementById('clickme').onclick = function (e) {
e.preventDefault();
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
}
Using Javascript
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);
Using jQuery
$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');
Try this out:-
http://jsfiddle.net/adiioo7/vmfbA/
Use
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
instead of
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
Edit:-
Ideally you should use body.appendChild method instead of changing the innerHTML
var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Instead of replacing everything with innerHTML try:
document.body.appendChild(myExtraNode);
improving the post of #Peter T, by gathering all solutions together at one place.
Element.insertAdjacentHTML()
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[#id="answer-33669996"]';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
The most underrated method is insertAdjacentElement.
You can literally add your HTML using one single line.
document.body.insertAdjacentElement('beforeend', html)
Read about it here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
The modern way is to use ParentNode.append(), like so:
let element = document.createElement('div');
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.append(element);
You can make your div HTML code and set it directly into body(Or any element) with following code:
var divStr = '<div class="text-warning">Some html</div>';
document.getElementsByTagName('body')[0].innerHTML += divStr;
Try doing
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>'
The best and better way is to create an element and append it to the body tag.
Second way is to first get the innerHTML property of body and add code with it. For example:
var b = document.getElementsByTagName('body');
b.innerHTML = b.innerHTML + "Your code";
Here's a really quick trick:
Let's say you wanna add p tag inside div tag.
<div>
<p><script>document.write(<variablename>)</script></p>
</div>
And that's it.

Categories

Resources