I am trying to simply append a textNode to <h1> and then append it to the body into a <div id="prob3">, but I get this error TypeError: bdy.appendChild is not a function on bdy.appendChild(header);. What is wrong with this piece of code?
JavaScript Code (embedded in the head tag):
function init()
{
var bdy = document.getElementsByTagName("body");
var header = document.createElement("h1");
var txt = document.createTextNode("Hello World!");
header.appendChild(txt);
bdy.appendChild(header);
}
HTML:
<body onload="init();">
<div id="prob3">
<!--Created TextNode goes Here-->
</div>
</body>
You can just use:
document.body.appendChild(header);
Your code wasn't working because:
var bdy = document.getElementsByTagName("body");
retrieves a list of elements, not a single element. You could have used:
var bdy = document.getElementsByTagName("body")[0];
to get the first element from the list, but there's no point in doing it this way since document.body is already predefined for you.
getElementsByTagName gets you a NodeList, and you can’t append to that – you would have to get out the first element of that list first, getElementsByTagName("body")[0].appendChild.
But every browser understands document.body as a shortcut to the body element.
In this method call:
var bdy = document.getElementsByTagName("body");
Notice "elements" is plural. Which means in all likelihood it returns an array-like structure (in this case a NodeList). Arrays naturally don't have a .appendChild method. You can tell this by inspecting bdy in a debugger, or more bluntly by console.log-ing it.
Related
Example:
var buttonHTML = "<button>MyButton</button>";
document.getElementById("myDiv").append(buttonHTML);
In this case, the function ends up appending the text into the div.
However, if I do the same with JQ:
$("#myDiv").append(buttonHTML);
In this case it will actually append the button.
Now, for various reasons, I have to use plain JS (not JQ).
Anyone have any ideas?
I am not sure how it worked with you and appended the element as text here, because there is no .append function in pure JS
But I agree with what #Sam Judge said in his answer,and also want to mention that you can do it using javascript without creating nodes one by one using javascript function Element.insertAdjacentHTML()
insertAdjacentHTML() parses the specified text as HTML or XML and
inserts the resulting nodes into the DOM tree at a specified position.
It does not reparse the element it is being used on and thus it does
not corrupt the existing elements inside the element. This avoiding
the extra step of serialization make it much faster than direct
innerHTML manipulation.
And there is another option to do the same using the .innerHTML but for sure you will need to save what's already inside to do the append effect.
This is because your var buttonHTML is just a string of text, if you append it as a child, it will create a DOM textNode, rather than an elementNode. What you want to do instead is something along the lines of the following :
var buttonHTML = document.createElement("button");
var buttonText = document.createTextNode("MyButton");
buttonHTML.appendChild(buttonText);
document.getElementById("myDiv").appendChild(buttonHTML)
you can try this code
function myFunction() {
var myButton= document.createElement("button");
myButton.style.width = "100px";
myButton.style.height = "30px";
myButton.style.background = "grey";
myButton.style.color = "white";
myButton.innerHTML = "MyButton";
document.getElementById("demo1").appendChild(myButton);
}
<button type="button" onclick="myFunction()">create another button</button>
<p id="demo1"></p>
I am new to javascript, thus I'm trying to teach myself the basics without using packages like JQuery, in order to better understand the language.
My question is in regards to creating an html tag within another html tag using only javascript, I can't seem to do this without getting an error (posted at the bottom).
For example what I have been trying to do is make the element children of each other through the following:
<!doctype html>
<html>
<head>
</head>
<body>
<script>
var element1 = document.createElement("div");
var element2 = document.createElement("svg");
var element3 = document.createElement("rect");
element1.setAttribute('id', 'div1');
element2.setAttribute('id', 'out');
//This is where I fall short
//One way i have tried
document.getElementById('div1').appendChild(element2);
document.getElementById('out').appendChild(element3);
//another way I have tried
document.getElementByClassName('div').appendChild(element2);
//last way I tried
document.getElementById('div1').innerHTML = element2;
</script>
</body>
</html
Although, i have been trying to make this work I have been coming up short and because of this I keep getting the error
"TypeError: 'null' is not an object (evaluating 'document.getElementBy(Id/ClassName)
().innerHTML/appendChild')
Any help is greatly appreciated! Also, if it's not too much to ask, since i am still trying to understand the javaScript concepts please explain your response.
The problem is that document.getElementById('div1') can only work once the element is in the document, as it is you already have a reference to that node, however, so use that:
element1.appendChild (element2);
Or:
document.body.appendChild(element1);
document.getElementById ('div1').appendChild (element2);
Which appends the node to the <body> element, and then searches the document for the element by its id.
You have to append the elements to the body before getting the element as they don't exist in the DOM.
var element1 = document.createElement("div");
var element2 = document.createElement("svg");
var element3 = document.createElement("rect");
element1.setAttribute('id', 'div1');
element2.setAttribute('id', 'out');
//you missed these.
document.body.append(element1);
document.body.append(element2);
document.getElementById('div1').appendChild(element2);
document.getElementById('out').appendChild(element3);
i'm having some trouble with javascript. Somehow i can't get started (or saying i'm not getting any results) with html elements creation by javascript.
i'm not allowed to use:
document.writeln("<h1>...</h1>");
i've tried this:
document.getElementsByTagName('body').appendChild('h1');
document.getElementsByTagName('h1').innerHTML = 'teeeekst';
and this:
var element = document.createElement('h1');
element.appendChild(document.createTextNode('text'));
but my browser isn't showing any text. When i put an alert in this code block, it does show. So i know the code is being reached.
for this school assignment i need to set the entire html, which normally goes into the body, by javascript.
any small working code sample to set a h1 or a div?
my complete code:
<html>
<head>
<title>A boring website</title>
<link rel="stylesheet" type="text/css" href="createDom.css">
<script type="text/javascript">
var element = document.createElement('h1');
element.innerHTML = "Since when?";
document.body.appendChild(element);
</script>
</head>
<body>
</body>
</html>
getElementsByTagName returns a NodeList (which is like an array of elements), not an element. You need to iterate over it, or at least pick an item from it, and access the properties of the elements inside it. (The body element is more easily referenced as document.body though.)
appendChild expects an Node, not a string.
var h1 = document.createElement('h1');
var content = document.createTextNode('text');
h1.appendChild(content);
document.body.appendChild(h1);
You also have to make sure that the code does not run before the body exists as it does in your edited question.
The simplest way to do this is to wrap it in a function that runs onload.
window.onload = function () {
var h1 = document.createElement('h1');
var content = document.createTextNode('text');
h1.appendChild(content);
document.body.appendChild(h1);
}
… but it is generally a better idea to use a library that abstracts the various robust event handling systems in browsers.
Did you append the element to document?
Much the same way you're appending text nodes to the newly created element, you must also append the element to a target element of the DOM.
So for example, if you want to append the new element to a <div id="target"> somewhere are the page, you must first get the element as target and then append.
//where you want the new element to do
var target = document.getElementById('target');
// create the new element
var element = document.createElement('h1');
element.appendChild(document.createTextNode('text'));
// append
target.appendChild(element);
create element, add html content and append to body
var element = document.createElement('h1');
element.innerHTML = 'teeeekst';
document.body.appendChild(element);
I am learning this stuff and trying to understand it, so am using this instead of innerhtml.
My code:
<script>
function load() {
"use strict";
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
var b = document.createElement("b");
b.appendChild(document.createTextNode(" name!"));
td.appendChild(document.createTextNode("Hello"));
td.appendChild(b);
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
t.border=1;
// note the reverse order of adding child
tr.appendChild(td);
tb.appendChild(tr);
t.appendChild(tb);
// more code to populate table rows and cells
document.getElementById("theBlah").appendChild(t);
alert(t.innerHTML);
}
</script>
</head>
<body onload="load()">
problem is , onload() does not display the <table> tag, it displays from <tbody> instead... any idea why?
And finally, in this code:
var t = document.createElement("table"),
tb = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
even though I am using the Var keyword just for t, and not for the others, why is it not complaining even though "use strict" is on? In fact if I add a "var" in front of "tb, "tr", "td" then it throws an error...
Thanks!
1) innerHTML is just that. It's inner. It doesn't contain the HTML of the element itself, but all the html that is within that element. There is a property called outerHTML too, but it's not included in Firefox. The only cross browser way to get outerHTML is to wrap the node in a new parent node and grab that nodes innerHTML. You can't just grab the current parent's innerHTML (You have to make a new parent) unless you're sure the element has no siblings, because if you do the siblings will included.
2) You are using commas to separate your variable decorations. That is the same as using semi-colons and putting var on each line.
InnerHtml is faster even though it's not in the spec. Its just the inner html like the above person said and not an element.
Using one Var and commas to separate your variable decorations is a good idea,
1. to reduce file size,
2. to declare all variables at the top. (to avoid hoisting problem)
I'm having some serious trouble getting my code to work in IE9, works fine in Chrome & Firefox but I throws some errors. Here are my 2 functions:
function insertHTML(content){
var body=document.getElementsByTagName('body');
body[0].appendChild(createElement(content));
}
function createElement(string){
var container=document.createElement('div');
container.innerHTML=string;
var element=container.firstChild.cloneNode(true);
return element;
}
I've tried severel methods for this and none seem to work, I'll explain exactly what I need to do...
...I need to create a new element from an html string, the string is sent back from an ajax call so my script will have almost no idea what it contains until it gets it.
I did try using element.innerHTML but this is no good, because if i have one html element (form) on the screen and the user enters data into it, and then when another element is inserted it will wipe all the user-entered data from the first form. I was doing element.innerHTML+=newData;
So basically, I need 2 things:
1) A way to create a new element from an html string.
2) A way to append the element to the document body.
It all needs to work cross-browser and I'm not allowed to use jQuery, also the new element cannot be contained in a div parent item, it has to have the body as its parent.
Thanks very much for your help,
Richard
innerHTML is read write and will destroy anything inside your div. use with extreme care
function insertHTML( htmlString ){
var bodEle = document.getElementsByTagName('body');
var divEle = createElement("div");
divEle.innerHTML = htmlString;
bodEle.appendChild(divEle);
}
So basically, I need 2 things:
A way to create a new element from an html string.
A way to append the element to the document body.
It all needs to work cross-browser and I'm not allowed to use jQuery, also the new element cannot be contained in a div parent item, it has to have the body as its parent.
The following was tested in IE8
<!DOCTYPE html>
<html>
<body>
<script>
var divBefore = document.createElement('div');
var divAfter = document.createElement('div');
var htmlBefore = '<span><span style="font-weight: bold">This bold text</span> was added before</span>';
var htmlAfter = '<span><span style="font-weight: bold">This bold text</span> was added after</span>';
divBefore.innerHTML = htmlBefore;
divAfter.innerHTML = htmlAfter;
document.body.appendChild(divBefore);
setTimeout(function() {
document.body.appendChild(divAfter);
}, 0);
</script>
<div>This content was here first</div>
</body>
</html>
Renders
This bold text was added before
This content was here first
This bold text was added after
https://www.browserstack.com/screenshots/7e166dc72b636d3dffdd3739a19ff8956e9cea96
In the above example, if you don't need to be able to prepend to the body (i.e. insert content before what already exists), then simply place the script tag after the original content and don't use setTimeout.
<!DOCTYPE html>
<html>
<body>
<div>This content was here first</div>
<script>
var divAfter = document.createElement('div');
var htmlAfter = '<span><span style="font-weight: bold">This bold text</span> was added after</span>';
divAfter.innerHTML = htmlAfter;
document.body.appendChild(divAfter);
</script>
</body>
</html>