Javascript:DIV AppendChild - javascript

In the below code "objTo" is a div to which i need to insert multiple number of div.
when i use the code for the first time its working.but on the next time its overwriting the existing code.
<script>
var divtest= document.createElement("div");
divtest.innerHTML = "<div>new div</div>"
objTo.appendChild(divtest)
</script>
Where am i going wrong?

I have made a very simple working version for you :
http://jsfiddle.net/hQKy9/
Multiple clicks works the whole time :
Script
function addDiv() {
var objTo = document.getElementById('container');
var divtest = document.createElement("div");
divtest.innerHTML = "new div";
objTo.appendChild(divtest);
}
Html
<div id="container"></div>
<input type="button" onclick="addDiv();" value="Click here to add div"/>

Even through Marc gave the ans before
I found it we can do more like adding ID/Class and CSS like the following way I did
const newChild = document.createElement('div');
newChild.id = 'newly_content';
newChild.innerHTML = `
<p style="font-size: 30px;padding: 200px 0px 10px 0px;">
A new content has been created!
</p>
`;
document.getElementById('ItemID').appendChild(newChild);

Related

Adding br tag in innerHTML between text and image

In my javascript program I have created div and added image and some hardcoded text in div by using innerHTML. But I am trying to add dynamic br tag between text and image. First text should be displayed then want to line break and then image should be displayed. So created br and added but somehow it doesn't work. Can anyone correct me ?
code:
function useInnerHTML() {
var movieText2 = prompt("One of my favourite movies");
var textNode = document.createTextNode(movieText2);
ele.appendChild(textNode);
document.body.appendChild(ele);
var newDiv2 = document.createElement("div");
var br = document.createElement("br");
newDiv2.className = "green";
var pic = "A picture is worth a thousand words";
var text2 = '<img src=\'https://i.stack.imgur.com/meXYL.png\'>';
newDiv2.innerHTML = pic + text2;
document.body.appendChild(newDiv2);
document.body.appendChild(br);
}
useInnerHTML();
.pink {
background-color: pink;
}
.green {
background-color: #71e887;
}
my output:
![output][1]
Simply use
pic = "A picture is worth a thousand words <br>";
since by using .innerHTML the <br> tag will not be escaped and actually embedded into the HTML as a breakline Element.
Or
Use Template strings and insertAdjacentHTML
function addNewMovie() {
var movieName = prompt("One of my favourite movies").trim(); // Trim it!
if(!movieName) return; // do nothing if empty!
var movieTemplate = `
<div class="movie">
<h1>${movieName}</h1>
<div class="green">
A picture is worth a thousand words<br>
<img src='//placehold.it/100x100/0bf'>
</div>
</div>
`;
document.body.insertAdjacentHTML("beforeend", movieTemplate);
}
<button onclick="addNewMovie()">ADD NEW MOVIE</button>
...cleaner, nicer.
You are adding the <br> after the picture, try doing it like this:
newDiv2.innerHTML = pic + br + text2;
document.body.appendChild(newDiv2);

Deleting specific div's with JavaScript

I am trying to spawn different div's and remove them after they do their job. A simple version of my code is:
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(child);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"?\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>'
The problem is that when the first spawned div is deleted, all div's are deleted. Any help is appreciated on how to fix this.
How about something like this:
function eraseDiv(target){
var div = target.parentNode;
var container = div.parentNode;
container.removeChild(div);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<button onclick=eraseDiv(this);> Delete</button>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<button type="button" name="submit" onclick="spawnDiv();">Spawn</button>
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
First thing, since you're returning false every time you obviously don't want to use the submit functionality of your submit input, so change it to a button instead.
Second thing, remove the ID from the spawned div since you should never have two divs with the same ID.
Third thing (like the first thing) since you're not using the link functionality of the anchor element, you should change it to a button instead (using CSS you can style this like an anchor if you want to).
Fourth thing, inside the delete button, add this as a parameter to the eraseDiv function. You can now access the button that was clicked using the function parameter rather than trying to find it by an ID.
The simplest fix to your code without modifying the functionality (and view of the page) of what you did is to replace the href="?" with href="#".
In your original code, when you do something like link with the "?" as the hyperlink, this actually performs a GET request which will reload the page. This is tricky because it makes it seem like your delete code is removing all the spawned divs from both cn1 and cn2 divs.
Changing the href=? to href=# prevents a GET request from happening. Below is a snippet that directly makes this change that results in the correct behavior of your original code (by deleting the spawned element in cn1). You will have to further modify your code to make it do what you want.
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(c);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"#\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
Another way of doing it would be to create a id for div like this
<html>
<body>
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
<script>
function eraseDiv(j){
var c = document.getElementById('child'+j);
c.parentNode.removeChild(c);
}
var i=1;
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child"+i;
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<u ><a onclick=eraseDiv("+i+++"); > Delete</a></u>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
</script>
</body>
</html>

How could I add the same string on different paragraph multiple time on the same HTML page?

I wish to know the best way to write only once the same thing and repeat inside the same page. For example:
<div>
<p id="description1"></p>
</div>
<div>
<p id="description1"></p>
</div>
--
I wish to write only one time the description1 inside the body. I think this could be achieved using the DOM.
Put the elements in the same class using the class attribute, then get the list of all elements using the getElementsByClassName() DOM function. You can then go over the list using a for loop.
[].forEach.call(document.getElementsByClassName("description"), function(elem) {
elem.innerHTML = "StackOverflow saved my day!";
});
You can even put the text in all elements of the same class using no JavaScript and only CSS by using the content attribute.
First of all, the ID field should be unique per element.
If you give all the tags a class <p class="description"></p> then you can use jQuery to set them all by calling:
$('.description').text('This is the text')
In javascript:
var elements = document.getElementsByClassName("description");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is the text.";
}
Have a look at the solutions proposed here
How to repeat div using jQuery or JavaScript?
this one seems to work pretty well:
html:
<div id="container">data</div>
js:
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
JSFIDDLE
Just added with a code by using
getElementsByClassName()
`<html>
<body>
<div class="example">First div element with class="example".</div>
<p class="example">Second paragraph element with class="example".</p>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i=0;i< x.length;i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>`
If you wish to keep id, change your code like this :
script :
var pcount = 2// # p
var desc = document.getElementById('description1');
for(i=0; i<pcount;i++){
document.getElementById('description' + i).innerHTML = desc;
}
html
<div>
<p id="description1"></p>
</div>
<div>
<p id="description2"></p>
</div>
two elements cannot have same id but can have same class
<head>
<script>
var x = document.getElementsByClassName("description");
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = "This is the text.";
}
</script>
<style>
.description1 { // this will apply the same style to all elements having class as description1
text-align: center;
color: red;
}
</style>
</head>
<body>
<div>
<p class="description1"></p>
</div>
<div>
<p class="description1"></p>
</div>
</body>
See the script tag. this solves your problem

First javascript function/link stops working?

Im fairly new to javascript and i'm trying to do a simple function where my div can be changed with a click of a link. Everything works fine except for when I click on my first link again, it stops working. The others continue to work...
Here is my code...hope someone can help me! Thanks!
<script>
function changedivVIDEO(){
var div = document.getElementById("fw14video");
div.innerHTML = "<div id='main2'>Hello</div>";
}
function changedivCAMPAIGN(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main3'>Hello</div>";
}
function changedivRUNWAY(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>Hello</div>";
}
</script>
<div id="main">
<div id="fw14video"></div>
<div id="fw14campaign"></div>
<div id="fw14runway"></div>
<div id="fw14runway"></div>
</div>
<p><h3>VIDEO</h3></p>
<p><h3>CAMPAIGN</h3></p>
<p><h3>RUNWAY</h3></p>
<p><h3>ACCESSORIES</h3></p>
</div>
I made an example that fills in the details I think are missing:
<div id="fw14video"></div>
<div id="fw14campaign"></div>
changediv1
changediv2
changediv3
<script>
function changediv1(e){
var div = document.getElementById("fw14video");
div.innerHTML = "<div id='main2'>div1</div>";
e.preventDefault();
}
function changediv2(e){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main3'>div2</div>";
e.preventDefault();
}
function changediv3(e){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>div3</div>";
e.preventDefault();
}
</script>
This works as intended. I am using e.preventDefault() to make it not follow the links, and set text different so you can tell which got clicked. Some questions:
do you mean for the IDs to be different?
how did you bind your functions to the links? (I used onclick.)
I think this:
function changedivRUNWAY(){
var div = document.getElementById("fw14campaign");
div.innerHTML = "<div id='main4'>Hello</div>";
}
Should be:
function changedivRUNWAY(){
var div = document.getElementById("fw14runway");
div.innerHTML = "<div id='main4'>Hello</div>";
}
As a starter...and then if nothing else is missing in the code you posted there's a lose < /div> tag.

Writing HTML to new window opened issue

I have this code:
<div class="col3">
<a id = "training-launch-button" href="javascript:void(0);" title=" My title here" class="button" onClick="Test();">Launch</a>
</div>
function Test() {
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
new_window.document.createElement("div");
document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
}
something is not right, I dont see the ordered list item?
I eventually want to build some HTML in the new window.
Use this Js
function Test() {
var newWindow= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var newContent = "<HTML><HEAD><TITLE>One Sub Window</TITLE></HEAD>";
newContent += "<BODY><div><ol><li>html data</li></ol></div>";
newContent += "</BODY></HTML>";
newWindow.document.write(newContent);
newWindow.document.close();
}
I think this is your problem; getElementsByName returns an array, not one element, so;
new_window.document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
NB: I have a '[0]' in there
I would try
new_window.document.getElementsByTagName('div')[0].innerHTML = ...
This should do it:
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement('div');
new_window.document.body.appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
You are actually not appending the new div to the new document's body, you'll have to use .appendChild() method for that, see this :
function Test() {
var new_window = window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement("div");
new_window.document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
}
see here - working example

Categories

Resources