Javascript Function to Remove Div - javascript

I need a function that can delete the div one by one .
My code is shown below. in my code i have created a function to create a div when i click a button . and i can't figure how to delete div one by one .
Please help me with the correct code to delete div one by one.
<html>
<head>
</head>
<body>
<button id="buttonone" onclick="creatediv()">CREATE A DIV</button>
<button id="buttontwo" onlick="removedivider()">Remove DIV </button>
<script>
function creatediv()
{
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("div");
newdiv.setAttribute("id","newdiv");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
//Function to Remove the DIV one by one;
}
</script>
</body>
</html>

<script>
var index = 0;
function creatediv()
{
++index;
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("span");
newdiv.setAttribute("id","newdiv" + index);
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
document.body.removeChild(document.getElementById("newdiv" + index));
--index;
}
</script>
Should work, I didn't test.

You weren't very clear regarding which div should be removed. Also, in your code, you repeatedly appended divs with the same id. You can't do that.
I made a quick example that removes the div appended first (a queue). I gave each date an id based on the current time, but such isn't really necessary. You could always just remove the first child of the parent div to which you are appending these divs.
However, if you plan on appending these divs in places that are not necessarily all under the same parent, then giving them unique ids and storing said ids is useful.
fiddle
HTML
<button id="add">add</button>
<button id="remove">remove</button>
<div id="holder">
<p>Added divs will go here</p>
</div>
JavaScript
var ids = [];
document.getElementById("add").onclick = function () {
var id = new Date().getTime(), // generate unique id (sort of)
div = document.createElement("div"); // create a div element
ids.push(id); // push the generated id to the holder array, ids
div.appendChild(document.createTextNode(id)); // append a text node to the div
div.setAttribute("class", "newDiv"); // give it a class for styling
div.setAttribute("id", id); // set its id
document.getElementById("holder").appendChild(div); // append the div
}
document.getElementById("remove").onclick = function () {
if (ids.length) { // only perform if a div has been appended
var div = document.getElementById(ids.shift());
// ids.shift() removes and returns ids[0], or the earliest added div
// this finds that element in the DOM
div.parentNode.removeChild(div); // and removes it
} else { // otherwise alert that there are no divs to remove
alert("no divs to remove!");
}
}
CSS
.newDiv {
height: 20px;
width: 110px;
background-color: #7EA8CA;
border: solid 1px #93CC76;
}

Replace your code with the following
<!DOCTYPE html>
<html>
<head>
<title>DIVs</title>
<script type="text/javascript">
function create_div() {
document.getElementById("button1").innerHTML="CREATE ANOTHER DIV";
var div = document.createElement("DIV");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
div.appendChild(text);
div.style.color = "white";
div.style.width = "100px";
div.style.backgroundColor = "green";
document.body.appendChild(div);
}
function remove_div() {
var div = document.getElementsByTagName('DIV'), i;
for(i = div.length-1; i >= 0; i--){
div[i].parentNode.removeChild(div[i]);
return false;
}
}
</script>
</head>
<body>
<button id="button1" onclick="create_div()">CREATE DIV</button>
<button id="button2" onclick="remove_div()">REMOVE DIV</button>
</body>
</html>
By the way, you can't have multiple DIVs having the same ID. Check the working jsBin

This function assumes there will be no other div elements. It will also remove the divs in fifo order.
function removedivider() {
var divs = document.getElementsByTagName('div');
if (divs.length > 0) divs[0].remove();
}
EDIT:
Here's a jsfiddle

Related

jquery dynamic content generated by dynamic content

(function(){
if (typeof $(".grid") === "undefined") {
return false;
} else {
var count = 0;
var images_to_place_container = ".grid";
for (var image in images_to_place) {
$(images_to_place_container).prepend("<div class = grid-item><div class=grid-item-hover></div></div>");
count++;
}
}
})();
I have this code that is dynamically generating images for a site, now what I want is that when I hover over one of these elements, I want to dynamically generate a div that is the same size and in the same position as the dynamically generated object I hovered over . Also, all elements are absolutely positioned using CSS. Thanks.
<body>
<div class='container'>
</div>
</body>
<script>
$(document).ready(function(){
//this dynamically "creates" the images...
$(".container").append("<img src='something.png' class='abc'>");
//this watches for click triggers on dynamically created elements
$(".container").on("click", "img.abc", function(){
var pos_top = $(this).css("top");
var pos_left = $(this).css("left");
var obj = "<div class='def'></div>";
$(obj).css("top", pos_top);
$(obJ).css("left", pos_left);
$(".container").append(obj);
});
});
</script>
Give classes abc and def the necessary css rules such as position, margin etc.

How to show/hide content

I have a page where I would like two buttons which when one is clicked, displays hello, and when the other one is clicked would hide the "hello" message and then display "goodbye". I know this needs to be done in javascript but I am not good with javascript.
Check this snippet
<p id="msg"></p>
<button onclick="helloFunction()">Say Hello</button>
<button onclick="byeFunction()">Wave Goodbye</button>
<script>
function helloFunction() {
document.getElementById("msg").innerHTML = "Hello";
}
function byeFunction() {
document.getElementById("msg").innerHTML = "Goodbye";
}
</script>
There are a couple of ways to do it, one of which would be affecting the visiblity of dom elements which say hello or goodbye, the other method as illustrated below you would actually change the text of a dom object based on which button is pressed
<button onClick="javascript:say('Hello');">Say Hi</button>
<button onClick="javascript:say('Goodbye');">Say Goodbye</button>
<div id="TextField"></div>
<script>
function say(text) {
var element = document.getElementById("TextField");
element.innerHTML = text;
}
</script>
here what you'll need to achieve such a feat.
first create a div or a p tag to hold ur text and two buttons
eg
<div id="container">Hello</div>
<button id="show">Show</button>
<button id="hide">Show</button>
make sure your div has an id and you buttons too. You use that for reference.
then in your javascript, you can either toggle the display or visibility of the div
<script type="text/javascript">
//Declare variable
var div = document.getElementById("container");
var show = document.getElementById("show");
var hide = document.getElementById("hide");
//run when windows fully loads
window.onload = function(){
//when i click show button
show.onclick = function(){
div.style.display = "block";
}
//when i click hide button
hide.onclick = function(){
div.style.display = "none";
}
}
//That is champ, this is all vanilla javascript. You can also look into implementing with jquery.
</script>

How to add Elements to DOM

I need a function which creates element and than adds text to that element and than adds that new element to a some location in DOM. I am noob to this.
I find this function but I don't know how to automaticaly specify location so that I can just call function and for example specify third argument as an element to which I want to append new element.
function appendElement (elemNode,textNode) {
var element = document.createElement(elemNode);
var text = document.createTextNode(textNode);
element.appendChild(text);
document.body.appendChild(element);
}
appendElement("b","lorem");
function appendElement (elemNode,textNode,containerToAppend) {
var container = document.getElementById(containerToAppend);
var element = document.createElement(elemNode);
var text = document.createTextNode(textNode);
element.appendChild(text);
container.appendChild(element);
}
appendElement("b","lorem","ContainerId");
Here's a way to do it in one line:
function appendElement (elemNode, textContent, parent) {
parent.appendChild(document.createElement(elemNode)).textContent = textContent;
}
appendElement("b","lorem", document.getElementById("container"));
div { background-color: aqua }
<div id="container"></div>
function appendElement (elemNode,textNode,containerToAppend) {
var container = document.getElementById(containerToAppend);
var element = document.createElement(elemNode);
var text = document.createTextNode(textNode);
element.appendChild(text);
container.appendChild(element);
}
appendElement("p","this is text","ContainerId");
Here is my attempt. Completely ripped off from developer.Mozilla.org with a minor tweak.
JSFIDDLE DEMO
Javascript:
function addElement() {
// Create a new div element and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //Add the text node to the newly created div.
// Add the newly created element and its content into the Parent of the clicked button
var parentDiv = event.target.parentNode;
document.body.insertBefore(newDiv, parentDiv);
}
HTML
<div id="div1">
<input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>
<div id="div2">
<input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>
<div id="div3">
<input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>

Is there any way to change CSS Class that registered in browser

I explain the problem by a simple example.
I have the following html page. It's simple.
There is one CSS Class named TestDiv and two javascript function.
addDiv creates new div and appends it to page by clicking on button "add new div".
setBlue is the function that i want to change the color of divs that has class TestDiv and I dont know how.
You can see that i wrote some code to change the current generated Divs inside the setBlue function. But I don't know how i can change the class to affect the new divs that will generated by addDiv function after that.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.TestDiv {
color:red;
}
</style>
<script>
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
}
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for(var i=0;i<currentDivList.length;i++){
currentDivList[i].style.color = "blue";
}
// What i can write here to change the TestDiv css class
// And after that, new (div)s will generate by new color(changed css class)
}
</script>
</head>
<body>
<div id="firstDiv" class="TestDiv">
test
</div>
<input type="button" value="add new div" onclick="addDiv();"/>
<input type="button" value="change color to blue" onclick="setBlue();"/>
</body>
</html>
I don't recommend adding or modifying CSS rules on-the-fly, but there are several solutions:
Modify the original CSS rule
<style id="myStyle">
.TestDiv {
color:red;
}
</style>
...
var myStyle = document.getElementById("myStyle");
myStyle.sheet.cssRules.item(0).cssText = ".TestDiv { color: blue }";
(I had to assign an ID to the style tag because I couldn't get it work in the jsFiddle environment otherwise. It should equally be possible by using document.styleSheets[0].)
Add a CSS rule to a newly created style sheet (thanks to pawel!)
var style = document.createElement('style');
document.head.appendChild(style);
style.sheet.addRule(".TestDiv", "color: blue");
Add raw CSS text to a newly created style sheet:
→ jsFiddle
var sheet = document.createElement('style')
sheet.innerHTML = ".TestDiv { color: blue }";
document.body.appendChild(sheet);
style.color creates an inline style that overrides the class styles. In order to retain whether setBlue() has been clicked store a var either isBlue = false or divClass = 'blue'/'red' and toggle a class on all the divs which retains your color styles:
http://jsbin.com/IdadUz/1/edit?html,css,js,output
You cannot directly modify style elements that have been created on the page or in external Style Sheets, one way to do this would be with the following javascript :
var newColor = '';
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
if (newColor != '') {
newDiv.style.color = newColor;
}
}
function setBlue() {
var currentDivList = document.getElementsByClassName("TestDiv");
for (var i = 0; i < currentDivList.length; i++) {
currentDivList[i].style.color = "blue";
}
newColor = 'blue';
}
When you click on the Change Color button it will set the newColor variable to blue. Then when you add a new div it will check if this variable has been set, if so it will change the style.
Example JSFiddle
I'd suggest adding a stylesheet to the head section:
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for (var i=0; i < currentDivList.length; i++) {
currentDivList[i].style.color = "blue";
}
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.innerHTML = ".TestDiv { color: blue; }";
head.appendChild(style);
}

JavaScript Getting ID of A Div

I have a div box with its id and an textarea.
When I click on my div box I should get div ID through Javascript and get it printed on the textarea. I have tried but its not working. when I click the text area it says "undefined". Kindly help me.
Here is the code:
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
getElementsByTagName returns a nodeList of DOM nodes, which acts like an array.
You'll need to select the first item in the node list before you can access the node's ID:
textEl.value = divEls[0].id;
Alternatively, you could have passed this to get_id():
function get_id(node) {
var textEl = document.getElementById('mytextarea');
textEl.value = node.id;
}
onclick="get_id(this)"
But honestly, all of the JavaScript should be external to your HTML file. HTML belongs in .html files, CSS belongs in .css files and JS belongs in .js files.
//i haven't checked this code, and you probably want to modify it to be more generic.
window.onload = function () {
var myDiv, myTextArea;
myDiv = document.getElementById('mydiv');
myTextArea = document.getElementById('mytextarea');
myDiv.onclick = function () {
myTextArea.value = myDiv.id;
};
};
Rewrite your code as below:
<html>
<head>
<script type="text/javascript">
function get_id(element) {
var textEl = document.getElementById("mytextarea");
textEl.value = element.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id(this)" style='border-width: 1px; border-color: #C0C0C0;
border-style: solid; background-color: #C0C0C0; width: 130px; height: 10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
When you use getElementsByTagName, you get ALL of the elements with that tag as an array.
If you want the first DIV then you need to add [0] this way:
var divEls = document.getElementsByTagName("div")[0];
The remaining code is ok.
getElementsByTagName returns an array even if it contains only one object. You should access it like this:
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls[0].id;
}
divels is, as the plural is indicating, an Array (correct: a NodeList), which has no id property. Its items have, so eg. textEl.value=divEls[0].id; will work (if the List is empty, this will throw an error).
try this function
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.item(0).id;
}
Ok I figured it out. document.getElementsByTagName("div") will return all the elements which have tag name div as an array of nodes. Here in your code there is only one div element hence first element is div itself. As in an array first element has number index = 0 so we can get first by document.getElementsByTagName("div")[0] or in your code divEls[0], and then we can get its id by simply getting divEls[0].id. Now as we have got the div id we can set the value of text area equal to this div id as: textEl.value = divEls[0].id Here is your code with changes. Hope this Helps
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
/*get the first item in the nodelist ie divEls[0] = document.getElementsByTagName("div")[0] and then get its id by
its id by divEls[0] */
textEl.value = divEls[0].id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>

Categories

Resources