Dynamically append Div in HTML JavaScript - javascript

I have created a div in HTML and want to add inner div dynamically to it. Below is the code for HTML:
<div id="table">
<div class="row">
This is the Demo First row Content.
<div class="cell1">
Cell 1 Content
</div>
<div class="cell2">
Cell 2 Content
</div>
</div>
<div class="row">
This is the Demo Second row Content.
<div class="cell1">
Cell 1 Content
</div>
<div class="cell2">
Cell 2 Content
</div>
</div>
</div>
<input type="button" value="Add New Row" onclick="addNewRow()" />
My CSS is:
div {
border: 1px dotted red;
padding: 10px;
}
And I have done the JavaScript for it but it is not working. The JavaScript is:
function addNewRow {
var table = document.getElementById('table');
var rDiv = document.createElement('div');
table.appendChild(rDiv);
rDiv.innerHTML = "This is the Demo Third row Content.";
var c1Div = document.createElement('div');
rDiv.appendChild(c1Div);
c1Div.innerHTML = "Cell 1 Content";
var c2Div = document.createElement('div');
rDiv.appendChild(c2Div);
c2Div.innerHTML = "Cell 2 Content";
}
But when I executed it, the new rows are not added. Please guide me what I am missing.

You have a typo preventing the execution of the function.
The correct name is document.getElementById (line 2 in JS).
You might want to enable the console (F12 IE debugger, Firebug, Developer Tools, etc) for debugging next time. These kinds of errors are very easy to spot.
Here is a working JsBin: http://jsbin.com/egImArO/1/edit

define javascript function like function addNewRow() { not a function addNewRow {

Just replace first js code line with this one:-
function addNewRow(){

Related

remove only the div inside the parent div

In this websites the user can add as much boxes as he wants, and every box contains a green and blue small boxes, the user should be able to click the blue box to remove the green box. the issue is that every time I click the blue box it doesn't remove the green box unless there is only one parent box is made. I have tried a lot of ways but nothing is working.
let count = 0;
function addBox() {
let box = `
<div class="box">
<div class="lbox" id="lbox">
</div>
<div class="rbox" id="rbox">
</div>
<h1>
${count}
</h1>
</div>
`
$(`#boxes`).append(box);
document.getElementById("lbox").addEventListener("click", function() {
rbox.remove();
})
count++;
}
If you have more than one parent box you need to iterate over each one.
You need to do something like;
let boxes = document.querySelectorAll('.box');
boxes.forEach(function(box){
box.querySelector('lbox').addEventListener('click',function(){
box.remove();
});
})
I haven't tested this, but the key part is the forEach function. This means everything you do inside the function is scoped to that box.
id must, at all times, be unique per-document. Learn about this very basic here: https://www.w3schools.com/hTML/html_id.asp. Your code keeps readding the same id values over and over, making your HTML invalid and your code dysfunctional.
Here's a working code example that doesn't rely on ids to get the job done:
let count = 0;
function addBox() {
let box = document.createElement('div');
box.className = 'box';
box.innerHTML = `
<div class="lbox">
</div>
<div class="rbox">
</div>
<h1>
${count}
</h1>`;
document.getElementById('boxes').appendChild(box);
box.querySelector('.lbox').addEventListener('click', function() {
box.querySelector('.rbox').remove();
})
count++;
}
.lbox, .rbox {
display: inline-block;
height: 40px;
width: 40px;
}
.lbox { background-color: blue; }
.rbox { background-color: green; }
<button onclick="addBox()">Add Box</button>
<div id="boxes"></div>
you need to define to delete the other box inside the same parent div.
I would delete the id because the defenition in class is the same.
I would also change the class names to something, wich makes visible what the green and what the blue box is.
You can do following:
let count = 0;
function addBox() {
let box = `
<div class="box_wrapper">
<div class="blue_box">
</div>
<div class="green_box">
</div>
<h1>
${count}
</h1>
</div>
`
$(`#boxes`).append(box);
$( ".blue_box" ).click(function() {
$(this).parent().find(".green_box").remove();
});
count++;
}
I think document.getElementById will always select the first element only with the given id. Therefore only the first lbox element in the dom keeps getting more and more eventlisteners attached to it, while the others won't get any. Make the id's of your elements unique by appending the count. That will make sure that every element gets it's eventlistener:
let count = 0;
function addBox() {
let box = `
<div class="box">
<div class="lbox" id="lbox${count}">
</div>
<div class="rbox" id="rbox${count}">
</div>
<h1>
${count}
</h1>
</div>
`;
$(`#boxes`).append(box);
document.getElementById("lbox" + count).addEventListener("click", function() {
$(".rbox" + count).remove();
})
count++;
}

HTML/JS open new url in half the page

I'm using HTML, CSS and Javascript. My page is divided into two vertical columns. On the right side, I have buttons that, when clicked, do add a sentence on the left side. What I want to do is, when I click a button, the sentence on the left side is printed AND the content on the right side changes. I tried just making a new url, but it changes de content of the whole page.
EDIT: what I want to do is like the software (point of sales) that restaurants use. One side is the receipt, the other is where the waitress clicks on the food and beverages and they appear on the receipt.
This is what I have, but none of it is about the new change in the column content:
function artfato() {
var x = document.getElementById("myDIV");
x.innerHTML = "1 Fato"
}
<div class="row">
<div class="column" style="background-color:#bbb;">
<h3>Ticket nº1</h3>
<p id="myDIV"></p>
</div>
<div class="column">
<table id="table">
<tr>
<td>
<input type="button" value="Fatos" class="ixbt" onclick="artfato();">
</td>
<td>
<input type="button" value="Calças" class="ixbt" onclick="artfato();">
</td>
</tr>
</table>
</div>
</div>
It seems your code currently is changing the contents of id="myDiv". Not sure exactly what you're looking for, but you most likely want to append something to each or one of your columns instead of overwriting it.
I am not sure if you looking for that, but here we go.
First of all, change the "myDiv" from paragraph to div.
<div id=myDiv></div>
After this you can change the event function (artfato) to something as below:
var x = document.getElementById("myDIV");
var makeIframe = document.createElement("iframe");
makeIframe.setAttribute("src", "http://aol.com");
makeIframe.setAttribute("scrolling", "no");
makeIframe.style.border = "none";
makeIframe.style.left = "-453px";
makeIframe.style.top = "-70px";
makeIframe.style.position = "absolute";
makeIframe.style.width = "1440px";
makeIframe.style.height = "775px";
x.appendChild(makeIframe);
style.position = "relative";
makediv.style.overflow = "hidden";
Do not forget to set the position attribute relative and absolute, to maintain the iframe inside div.
If you want to get content from your own origin (domain/application), try this:
<iframe sandbox="allow-forms allow-same-origin allow-scripts" src="https://yoururl.com/"></iframe>
font: stackoverflow answer

can I remove a line in my HTML code with javascript?

I have this code:
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>
and I want to make a javascript code to remove the div below the input field whenever I write anything in the input
..........
I tried this code:
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
var parent = field.parentNode;
parent.innerHTML = field.outerHTML;
field.value = num;
}
but it have a problem each time I make an input, I have to re-click inside the input to make it active again
check out the code here
You should not use inline HTML event attributes to wire up event handlers. That technique is 25+ years old and will not die the death it deserves because people just keep copying it from other code they've seen.
See the comments for the simple explanation:
// Add the event handler to the input in JavaScript, not in HTML
document.getElementById("myID").addEventListener("input", removeElement);
function removeElement(){
// Remove the sibling element that follows the input
document.querySelector("#myID").nextElementSibling.remove();
// Now that the element has been removed, this function is no
// longer required, so remove the event handler to prevent attempts
// to remove it again when it's no longer there. "this" refers to
// the object that caused this function to be invoked (the input
// element in this case).
this.removeEventListener("input", removeElement);
}
<div class="input">
<input type="number" id="myID">
<div>
<h3>MY TEXT</h3>
</div>
</div>
How to remove an HTML element using JavaScript ?
Given an HTML element and the task is to remove the HTML element from the document using JavaScript.
Approach:
Select the HTML element which need to remove.
Use JavaScript remove() and removeChild() method to remove the
element from the HTML document.
Exemple to remove a div :
div.parentNode.removeChild(div);
Follow this link for more information.
I hope I was able to help you.
<div class="input">
<input type="number" id="myID" >
<div id="id2">
<h3>MY TEXT</h3>
</div>
</div>
<script>
document.getElementById("myID").oninput = function() {myFunction()};
function myFunction() {
document.getElementById("id2").innerHTML="";
}
</script>
Problem with using innerHTML is you are basically using a whiteboard. You erase everything on it and you have to redraw it all. That means you would need to reset the value and focus. It is doable, just not practical.
The better thing to do would be to select the element and remove it with .remove()
var field = document.getElementById("myID");
var num = field.value;
if (num.length) {
field.nextElementSibling.remove()
}
It will work, but you will be better off using a class to hide the element. It also has the benefit that if the user deletes the text in the input, you can reshow the message. I would just hide it with a css class with toggle. I would select the div with nextElementSibling.
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
field.nextElementSibling.classList.toggle('hidden', num.length)
}
.hidden {
display: none;
}
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>

Repeat block of text for each DIV instance

I am trying to get text to showup after each post in my Tumblr theme, and the javascript works in the jsfiddle, but not when I include it into the theme. Am I missing something?
http://jsfiddle.net/KP3uw/70/
HTML
<div id="wrapper">
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div class="post">
<div class="stat-wrap"></div>
</div>
<div id="counter"></div>
</div>
JAVSCRIPT
/*global */
function statwrap() {
var count;
var counter;
var bob;
count = document.getElementsByTagName('div').length;
counter = document.getElementById('counter').innerHTML = count;
bob = document.getElementsByClassName('stat-wrap');
var i;
for (i = 0; i < counter; i++) {
bob[i].innerHTML = "jkfdgdff14";
}
}
window.onload = statwrap();
Here's my tumblr theme I have pasted the javascript into btw. (http://lgbtvee.tumblr.com/) I've tried both just above </head> and </body> ending tags but it didn't work either place.
I think you have made this wayy to complicated.
Try using jQuery and using the append() function:
$( ".stat-wrap" ).append( "<p>Test</p>" );
Example:
http://jsfiddle.net/KP3uw/74/
maybe it's not exactly answer to your question but you can add some content to all elements with css :after.
.stat-wrap:after {
content: "jkfdgdff14";
display: block;
}
demo: http://jsfiddle.net/t0ro94dz/
I would have made this a comment, but don't have enough reputation to do it yet.
Your loop's condition i < counter is off, I think. The variable counter is tied to innerHTML, which I believe is a string (not a number). Try changing it to i < count.
--edit--
I also noticed that your theme is throwing 2 of the same errors:
Uncaught TypeError: Cannot set property 'innerHTML' of null
since you don't actually have any elements with the ID of counter on the page. Also, in the page source, your script is repeated twice.
I dont know what is not working but there are so many divs. Maybe you want limit and say
count = document.getElementsByClassName('post').length;
Also can you check if you need to parse innerHTML into int using parseInt, some JS compilers can scream
document.getElementById('counter').innerHTML = count;
count = parseInt(document.getElementById('counter').innerHTML);
OR simply
document.getElementById('counter').innerHTML = count
counter = count

Javascript change div content upon a click

I'm pulling a content from PHP array and I have a situation like this:
<div class="weight-display">
<span>04/25/2011</span> <span>100lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc...
Now when somebody clicks on Edit within, let's say, first div where weight is 100lbs, I just need that "div" to change and to have input field instead of simple text where weight is (while others will remain the same) and to be like this:
<div class="weight-display">
<span>04/25/2011</span> <input type="text" value="100" /> <span>Save</span> <span>Cancel</span>
</div>
<div class="weight-display">
<span>04/27/2011</span> <span>150lbs</span> <span>Edit</span> <a href="http://foo.com">Delete</span>
</div>
etc..
So basically div has to "reload itself" and change content. Now I really need some very simple Javascript solution. Preferably I would like a solution with a hidden div beneath original one, so they just swap places when user clicks on EDIT and in a case if CANCEL is pressed to swap places again so original div with text is displayed...
Thanks,
Peter
<style type="text/css">
/* Normal mode */
.weight-display div.edit {display:none}
/* Editor mode */
.weight-edit div.show {display:none}
</style>
<div class="weight-display">
<button onclick="toggle(this)">Edit this!</button>
<div class="edit"><input type="text" value="Test" /></div>
<div class="show">Test</div>
</div>
<script type="text/javascript">
function toggle(button)
{
// Change the button caption
button.innerHTML = button.innerHTML=='Edit this!' ? 'Cancel' : 'Edit this!';
// Change the parent div's CSS class
var div = button.parentNode;
div.className = div.className=='weight-display' ? 'weight-edit' : 'weight-display';
}
</script>
What you suggest is basically correct. I would generate two div's one for display and one edit. The edit div will initially have display: none. When the Edit is clicked, hide the display div and show the edit div.
How about something like:
onClick event calls a function (EDITED to be a little smarter than my original brute force method):
function swapdivs ( id_of_topdiv, id_of_bottomdiv ) {
var topdiv = getRefToDiv( id_of_topdiv );
var bottomdiv = getRefToDiv( id_of_bottomdiv );
var temp = topdiv.style.zIndex;
topdiv = bottomdiv.style.zIndex;
bottomdiv = temp.style.zIndex;
}
Could that or similar work for you? Or am I missing some subtle yet crucial requirement?

Categories