createNewElement and appendChild to existing content - javascript

I am trying to understand JavaScript a little better and am having trouble creating elements and appending values to them.
All I want to do is create a new paragraph element, which will contain a new string, and add the paragraph to my existing div tag using appendChild.
var oldParagraph = document.getElementById('content')
var newParagraph = document.createElement('p');
var text = document.createTextNode("i am a new text node.");
newParagraph.setAttribute('class', 'red');
function addText(){
document.oldParagraph.appendChild(newParagraph);
document.newParagraph.appendChild(text);
}
my HTML is simple:
<div id="content"></div>

Your code should be this:
function addText(){
oldParagraph.appendChild(newParagraph);
newParagraph.appendChild(text);
}
oldParagraph and newParagraph are variables containing DOM object references. You operate on those DOM references directly.
In practice, I would think you'd organize your code more like this with local variables instead of global variables:
function addText() {
var newParagraph = document.createElement('p');
newParagraph.className = 'red';
newParagraph.appendChild(document.createTextNode("i am a new text node."));
document.getElementById('content').appendChild(newParagraph);
}
Working demo: http://jsfiddle.net/jfriend00/42ffq/.

Related

Javascript dynamic element creation leads to shadow content in HTML

I create a class and elements inside the class using the following function in javascript and add it to another class using appendchild function.
function createClass(menu)
{
console.log('class entered');
var newNode = document.createElement('div');
newNode.className = 'item';
var input = document.createElement('input');
input.setAttribute("type","checkbox");
input.setAttribute("id",menu);
input.innerText=menu;
var label = document.createElement('label');
label.setAttribute("for", menu);
label.innerText=menu;
input.appendChild(label);
newNode.appendChild(input);
return newNode;
}
But, the contents is not displayed in the html page. The class is added. When the body of the html is displayed in the console, the class is added to the body but before the inner text, it says "shadow content (user Agent)".
How do I make them visible?
You've create new DOM elements but never actually attached them to the current document. The missing part is to to add your new DOM element to the document:
document.body.appendChild(createClass('hello'))

How can I write down paragraphs in HTML with Javascript without the use of getElementbyId?

So, i was working on this little formatting experiment with HTML, where you could create a paragraph via input and it would create an HTML paragraph on the screen. I did it by doing this.
HTML:
<button onclick="create_para()">Create Paragraph</button>
<p id="p1"></p>
Javascript:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
document.getElementById("p1").innerHTML = p;
}
And, it worked! The only problem is that I wanted it so you could click the button again and again and it would create new paragraphs without replacing the old one. The only way I thought I could do it would be by making a bunch of tags with different classes, and having a bunch of functions, and a lot of buttons, but that's inefficient and too complicated.
So, I found out about document.write() and document.writeln(). So I used it in my code, but turns out it just deletes all other HTML code and just leaves it with the lines I wrote.
Therefore, is the a form of writing down paragraph lines without the use of ID's, or a form where it wouldn't delete all HTML code?
Thanks.
You can do something like:
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
document.body.appendChild(elem)
}
EDIT: to add an id to each, you can add a global counter variable.
var i = 0;
function create_para(){
var p = window.prompt("Enter paragraph text: ");
var elem = document.createElement('p');
elem.innerText = p;
elem.id = '' + i;
i++;
document.body.appendChild(elem);
}
You can create a div container and then creates HTML Elements dinamically with your function, also you can assing an id to your new element, try this:
let div = document.getElementById('container');
function create_para(){
let p = document.createElement('p');
let txt = window.prompt("Enter paragraph text: ");
p.textContent = txt;
p.id = 'your id';
div.appendChild(p);
}
<div id='container'></div>

how to show html when using appendChild

I'm creating some elements through this code in JavaScript:
var tdiv = document.createElement("div");
tdiv.setAttribute('id', 'titlediv');
var ddiv = document.createElement("div");
ddiv.setAttribute('id', 'datediv');
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
Now I have to append some html text to cdiv. I tried to do cdiv.appendChild() but it displays an error since it is not a node. Tried doing var newsupdate_ = document.createTextNode(global[j].content) then appending it but it looks like this:
Can I do setAttribute to place the content inside the desired div?
appendChild() would not work in cdiv because there is no such method present in the element created by createElement().
createTextNode() creates a new Text node. It will not evaluate any HTML present in the parameter string.
Try innerHTML like the following way:
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
cdiv.innerHTML = '<h1>Header 1</h1>';
document.getElementById('container').append(cdiv);
<div id="container"></div>
use innerHTML, example
document.getElementById("demo").innerHTML = "Paragraph changed!";

dynamically adding/removing a div to html

I want to dynamically create a div element with id="xyz". Now before creating this, I want to remove any other div with id ="xyz" if it exists. How can i do it?
var msgContainer = document.createElement('div');
msgContainer.setAttribute('id', 'xyz'); //set id
msgContainer.setAttribute('class', 'content done'); // i want to add a class to it. it this correct?
var msg2 = document.createTextNode(msg);
msgContainer.appendChild(msg2);
document.body.appendChild(msgContainer);
}
How can i remove all divs with id =xyz if they exist before executing above code?
Removing:
var div = document.getElementById('xyz');
if (div) {
div.parentNode.removeChild(div);
}
Or if you don't control the document and think it may be malformed:
var div = document.getElementById('xyz');
while (div) {
div.parentNode.removeChild(div);
div = document.getElementById('xyz');
}
(Alternatives below.)
But you only need the loop with invalid HTML documents; if you control the document, there's no need, simply ensure the document is valid. id values must be unique. And yet, one sees plenty of documents where they aren't.
Adding:
var msgContainer = document.createElement('div');
msgContainer.id = 'xyz'; // No setAttribute required
msgContainer.className = 'someClass' // No setAttribute required, note it's "className" to avoid conflict with JavaScript reserved word
msgContainer.appendChild(document.createTextNode(msg));
document.body.appendChild(msgContainer);
If you don't like the code duplication in my loop above and you think you need the loop, you could do:
var div;
while (!!(div = document.getElementById('xyz'))) {
div.parentNode.removeChild(div);
}
or
var div;
while (div = document.getElementById('xyz')) {
div.parentNode.removeChild(div);
}
...although that last may well generate lint warnings from various tools, since it looks like you have = where you mean == or === (but in this case, we really do mean =).

How to get the HTML for a DOM element in javascript

Imagine I have the following HTML:
<div><span><b>This is in bold</b></span></div>
I want to get the HTML for the div, including the div itself. Element.innerHTML only returns:
<span>...</span>
Any ideas? Thanks
Use outerHTML:
var el = document.getElementById( 'foo' );
alert( el.outerHTML );
Expanding on jldupont's answer, you could create a wrapping element on the fly:
var target = document.getElementById('myElement');
var wrap = document.createElement('div');
wrap.appendChild(target.cloneNode(true));
alert(wrap.innerHTML);
I am cloning the element to avoid having to remove and reinsert the element in the actual document. This might be expensive if the element you wish to print has a very large tree below it, though.
First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.
<div><span><b>This is in bold</b></span></div>
=>
<div id="wrap"><div><span><b>This is in bold</b></span></div></div>
and then:
var e=document.getElementById("wrap");
var content=e.innerHTML;
Note that outerHTML is not cross-browser compatible.
old question but for newcomers that come around :
document.querySelector('div').outerHTML
You'll want something like this for it to be cross browser.
function OuterHTML(element) {
var container = document.createElement("div");
container.appendChild(element.cloneNode(true));
return container.innerHTML;
}
If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-
function getHTML(who,lines){
if(!who || !who.tagName) return '';
var txt, ax, str, el= document.createElement('div');
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
ax= txt.indexOf('>')+1;
str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
el= null;
return lines? str.replace(/> *</g,'>\n<'): str;
//easier to read if elements are separated
}
var x = $('#container').get(0).outerHTML;
as outerHTML is IE only, use this function:
function getOuterHtml(node) {
var parent = node.parentNode;
var element = document.createElement(parent.tagName);
element.appendChild(node);
var html = element.innerHTML;
parent.appendChild(node);
return html;
}
creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom
define function outerHTML based on support for element.outerHTML:
var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
} else { // when .outerHTML is not supported
var outerHTML = function(el){
var clone = el.cloneNode(true);
temp_container.appendChild(clone);
outerhtml = temp_container.innerHTML;
temp_container.removeChild(clone);
return outerhtml;
};
};
var el = document.getElementById('foo');
el.parentNode.innerHTML;

Categories