Get all child nodes javascript - 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

Related

Document.createElement() vs Document.createTextNode() - Javascript

I'm trying to figure out what is the differences between this two:
// first one
var h1 = document.createElement('h1');
var t = document.createTextNode('hey');
h1.appendChild(t);
document.body.appendChild(h1);
// second one
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));
The first (Document.createElement()) works perfectly, but the second (Document.createTextNode()) does not.
The return value of appendChild is the appended child.
So if we add variables to:
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));
it gets broken down into:
var text = document.createTextNode('hey');
var h1 = document.createElement('h1');
h1.appendChild(text);
document.body.appendChild(text);
Appending the text to the body removes the text from the h1.
The h1 is discarded because it is never appended anywhere.
I find a way to do it: (just add .parentNode at the end)
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')).parentNode);

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

Adding larger content to div dynamically

I am using a div that is shown when I hover over an image. I want to use this div to display image info. How can I add a few lines of content to the div? The only sollution I found is innerHTML property of the div, but this means I have to use this for aech value I want to put on a div. Is there a way I can put more content on a div with a single command. I want to achieve this using javascript or dojo.
every time you use innerHTML the screen has to reflow/repaint. better pattern is to create a document fragment and update it "offline" before make the info "live":
var p, t, frag;
divInf = document.createElement('div');
frag = document.createDocumentFragment();
p = document.createElement('p');
t = document.createTextNode('first line');
p.appendChild(t);
frag.appendChild(p);
p = document.createElement('p');
t = document.createTextNode('second line');
p.appendChild(t);
frag.appendChild(p);
divInf.appendChild(frag);

Change some look for html on basis of selection of text

In my app there is an html file showed in a webview. I have a note functionality where when user selects text, it is highlighted and an image is added as suffix. This note is then saved as an html file.
So for this functionality, I have written a java script function.
function highlightsText()
{
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var newDate = new Date;
var randomnumber= newDate.getTime();
var div;
var imageTag = document.createElement("img");
imageTag.id=randomnumber;
imageTag.setAttribute("src","notes.png");
var linkTxt = document.createElement("a");
linkTxt.id=randomnumber;
linkTxt.setAttribute("href","highlight:"+randomnumber);
linkTxt.appendChild(selectionContents)
div = document.createElement("span");
div.style.backgroundColor = "yellow";
div.id=randomnumber;
linkTxt.appendChild(imageTag);
div.appendChild(linkTxt);
range.insertNode(div);
return document.body.innerHTML+"<noteseparator>"+randomnumber+"<noteseparator>"+range.toString();
}
Here I am making a span and this span holds my highlighted text with image.
Now problem is,
When I am selecting a paragraph, it only adds an image and does not highlight the text.
If I use div or p tag in place of span then it gives an entire line for a single word which looks rather odd.
Edit: div tags will get a linebreak before and after (usually, most browsers do this, considering it is a "division"/block level element), you're better off using a span.
And secondly you should append the selection contents to the span
ispain.appendChild(selectionContents) !! and do not forget the semicolon ;)
on a side note, you do know that:
1- you can't have html element ids starting with digits.
2- having more than one elements with the same id is gonna get unpredictable when you're selecting em.

How do you enclose unknown HTML in a div with plain 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.

Categories

Resources