How do you enclose unknown HTML in a div with plain Javascript? - javascript

I have an HTML page that has varying types of content. I would like to make a javascript function that when run encloses anything inside the <body> tag with a <div id="content-container">. Then I want to be able to add a <div id="verifying"></div> that new <div>. I think I know how to do this with jQuery, but I need to do it with plain Javascript.
Any idea as to how this would be done?

This is how I might do it.
var body = document.body;
var contentContainer = document.createElement('div');
contentContainer.id = 'content-container';
var node;
while (node = body.firstChild) {
contentContainer.appendChild(node);
}
body.appendChild(contentContainer);
var verifying = document.createElement('div');
verifying.id = 'verifying';
contentContainer.appendChild(verifying);
jsFiddle.

I haven't tested, but I imagine that you can take the innerHTML of document and set it to be itself along with whatever wrapper string (or div) you want.
Something along the lines of:
body = methodToLocateBodyInTheDom();
body.innerHTML = "<div id='content-container'>" + body.innerHTML + "</div>"
There are probably better ways, but I think something of that nature sure work.

Related

Get all child nodes javascript

Hi I am trying to add a html with a SPACE after in a contenteditable div;
The problem is that, with above code it only return the content of the first DIV and ignore everything else.
var tdiv = document.createElement('div');
tdiv.innerHTML = '<div>testing html</div> ';
var replacment = tdiv.firstChild; //
el.insertNode(replacment); // it is just the purpose, "el" is the HTML element
With this the nbsp will be removed.
If you want all children of tdiv to be added to el then try
var el = document.getElementById('x')
while (tdiv.firstChild) {
el.appendChild(tdiv.firstChild);
}
Demo: Fiddle
You can create an element with an nbsp in it like this:
var div = document.createElement("div");
div.innerHTML = " ";
If you really just want an element with a space of text, you can just create a text node:
var div = document.createElement("div");
div.appendChild(document.createTextNode(" "));
Looking at your question again, it is actually quite unclear what you're really asking and it appears that there are many different things your question might mean. So, this is just one possibility for what you might be asking.
If you want to add it as an element, then you need to put it in some sort of container since a non-breakingspace isn't an element by itself. You can wrap it in a <span> element like this and then insert the <span>.
var span = document.createElement("span");
span.innerHTML = " ";
el.appendChild(span);
Or, maybe it works just fine to insert a text node with a space in it:
el.appendChild(document.createTextNode(" "));
After Arun P Johny Idea I resolved like this:
var replacement = '<div>testing</div> ',startAfter,i,tdiv = document.createElement('div');
tdiv.innerHTML = replacment;
replacment=document.createDocumentFragment();
while(i=tdiv.firstChild) replacment.appendChild(i);
startAfter = replacment.lastChild;
// This is my extra code to the contenteditable div insert and positioning the caret - this.range is my selection range.
this.range.insertNode(replacment);
this.range.setStartAfter(startAfter);
Thank you all, even for the down votes :P

Appending elements to DOM with indentation/spacing

Here is an example. Check the console for the result. The first two divs (not appended; above the <script> in the console) have the proper spacing and indention. However, the second two divs do not show the same formatting or white space as the original even though they are completely the same, but appended.
For example the input
var newElem = document.createElement('div');
document.body.appendChild(newElem);
var another = document.createElement('div');
newElem.appendChild(another);
console.log(document.body.innerHTML);
Gives the output
<div><div></div></div>
When I want it to look like
<div>
<div></div>
</div>
Is there any way to generate the proper white space between appended elements and retain that spacing when obtaining it using innerHTML (or a possible similar means)? I need to be able to visually display the hierarchy and structure of the page I'm working on.
I have tried appending it within an element that is in the actual HTML but it has the same behavior
I'd be okay with doing it using text nodes and line breaks as lincolnk suggested, but it needs to affect dynamic results, meaning I cannot use the same .createTextNode(' </br>') because different elements are in different levels of the hierarchy
No jQuery please
I think you're asking to be able to append elements to the DOM, such that the string returned from document.body.innerHTML will be formatted with indentation etc. as if you'd typed it into a text editor, right?
If so, something like this might work:
function indentedAppend(parent,child) {
var indent = "",
elem = parent;
while (elem && elem !== document.body) {
indent += " ";
elem = elem.parentNode;
}
if (parent.hasChildNodes() && parent.lastChild.nodeType === 3 && /^\s*[\r\n]\s*$/.test(parent.lastChild.textContent)) {
parent.insertBefore(document.createTextNode("\n" + indent), parent.lastChild);
parent.insertBefore(child, parent.lastChild);
} else {
parent.appendChild(document.createTextNode("\n" + indent));
parent.appendChild(child);
parent.appendChild(document.createTextNode("\n" + indent.slice(0,-2)));
}
}
demo: http://jsbin.com/ilAsAki/28/edit
I've not put too much thought into it, so you might need to play with it, but it's a starting point at least.
Also, i've assumed an indentation of 2 spaces as that's what you seemed to be using.
Oh, and you'll obviously need to be careful when using this with a <pre> tag or anywhere the CSS is set to maintain the whitespace of the HTML.
You can use document.createTextNode() to add a string directly.
var ft = document.createElement('div');
document.body.appendChild(ft);
document.body.appendChild(document.createTextNode(' '));
var another = document.createElement('div');
document.body.appendChild(another);
console.log(document.body.innerHTML);

How can I strip down JavaScript code while building HTML?

I am trying to parse some HTML to find images within it.
For example, I created a dynamic div and parsed the tags like this:
var tmpDiv = document.createElement("DIV");
tmpDiv.innerHTML = html;
The HTML should be script-less however there are exceptions, one code segment had the following code under an image tag:
<img src=\"path" onload=\"NcodeImageResizer.createOn(this);\" />
By creating a temp div the "onload" function invoked itself and it created a JavaScript error.
Is there anyway to tell the browser to ignore JavaScript code while building the HTML element?
Edit:
I forgot to mention that later on I'd like to display this HTML inside a div in my document so I'm looking for a way to ignore script and not use string manipulations.
Thanks!
One way of doing this is to loop through the children of the div and remove the event handlers you wish.
Consider the following:
We have a variable containing some HTML which in turn has an onload event handler attached inline:
var html = "<img src=\"http://www.puppiesden.com/pics/1/doberman-puppy5.jpg\"
alt=\"\" onload=\"alert('hello')\" />"
One we create a container to put this HTML into, we can loop through the children and remove the relevant event handlers:
var newDiv = document.createElement("div");
$(newDiv).html(html);
$(newDiv).children().each(function(){this.onload = null});
Here's a working example: http://jsfiddle.net/XWrP3/
UPDATE
The OP is asking about removing other events at the same time. As far as I know there's no way to remove all events in an automatic way however you can simply set each one to null as required:
$(newDiv).children().each(function(){
this.onload = null;
this.onchange = null;
this.onclick = null;
});
You can do it really easily with jquery like this:
EDIT:
html
<div id="content" style="display:none">
<!-- dynamic -->
</div>
js
$("#content").append(
$(html_string).find('img').each(function(){
$(this).removeAttr("onload");
console.log($(this).attr("src"));
})
);

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

insert/remove HTML content between div tags

how can I insert some HTML code between <div id="mydiv">...</div> using javascript?
Ex: <div id="mydiv"><span class="prego">Something</span></div> its about 10 lines of html of most. thank you
If you're replacing the contents of the div and have the HTML as a string you can use the following:
document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
A simple way to do this with vanilla JavaScript would be to use appendChild.
var mydiv = document.getElementById("mydiv");
var mycontent = document.createElement("p");
mycontent.appendChild(document.createTextNode("This is a paragraph"));
mydiv.appendChild(mycontent);
Or you can use innerHTML as others have mentioned.
Or if you would like to use jQuery, the above example could be written as:
$("#mydiv").append("<p>This is a paragraph</p>");
// Build it using this variable
var content = "<span class='prego'>....content....</span>";
// Insert using this:
document.getElementById('mydiv').innerHTML = content;
That's really kind of an ambiguous request. There are many ways this can be accomplished.
document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
That is the simplest. OR;
var spn = document.createElement('span');
spn.innerHTML = 'Something';
spn.className = 'prego';
document.getElementById('mydiv').appendChild(spn);
Preferred to both of these methods would be to use a Javascript library that creates shortcut methods for the simple things like this, such as mootools. (http://mootools.net)
With mootools this task would look like:
new Element('span', {'html': 'Something','class':'prego'}).inject($('mydiv'));
document.getElementById("mydiv").innerHTML = "<span class='prego'>Something</span>";
Should do it. If you are willing to use jQuery it could be easier.
document.getElementById('mydiv').innerHTML = 'whatever';
Javascript
document.getElementById('mydiv').innerHTML = '<span class="prego">Something</span>';
jQuery
$("#mydiv").append('<span class="prego">Something</span>');

Categories

Resources