How to append multiple element into a parent element? [duplicate] - javascript

My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/

appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}

Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}

Related

get two Elements by Id in same js function [duplicate]

My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}

dynamically added div is not draggable

I'm trying to make my dynamically added divs draggable but if I call after
$("#draggable").draggable({});
this
for( var i = 0; i < 5; i++ ){
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
}
there is no chance to make divs draggable.
I know it works if i create divs first but I need to keep it like this because of my project and this example shows my problem.
Here is fiddle: http://jsfiddle.net/bimbochobot/9jstfwpm/4/
Thank you in advice.
You will have to initialize draggable widget after appending new element.
Try this fiddle:
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.backgroundColor = 'blue';
document.body.appendChild(smallone);
$(smallone).draggable({});
}
Use a class instead of id as id must be unique
$(".draggable").draggable({});
Assign draggable class to all divs
simple 1 ...
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
$(".smallDiv").draggable({});
}
it is working... http://jsfiddle.net/9jstfwpm/7/

Div's are being generated dynamically and even the (obj.search) fetches the data but nothing is being displayed in it. How do i display the data?

JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.

Delete Javascript generated HTML

I am programming a blackjack game and for each drawn card i create a tag <img> to display the card.
Naturally i have to delete this tag <img> after every game, but how can i do this?
Is there a way that I can remove all <img> tags within a parent?
Is there something like this: (Pseudecode)
div.removeAllChildElemtens()
or
div.removeChildElements("img");
Thanks.
If you create the elements using document.createElement('img') then you can keep a reference to them in order to delete them later.
var cards = [];
for (var i = 0; i < 52; i++)
{
var card = document.createElement('img');
// ... more initialisation of card
cards.push(card);
}
// later, to remove all
for (var i = 0; i < cards.length; i++)
{
var card = cards[i];
card.parentElement.removeChild(card);
}
Please, see the removeChild usage trick or use the new remove() function:
var div = document.getElementById("parentDivId");
var images = div.getElementsByTagName('img');
for(var i = 0; i < images.length; i++){
var img = images[i];
img.parentNode.removeChild(img);
//OR img.remove() as #Pete TNT pointed-out for modern web-browsers (FF/CH < 23)
}

Javascript - How to get all elements and do same thing on each of them

I want to get all DIVs in DIV(id = room) and do the same javascript code on each one.
I think it should look like this
Get element by id room -> Get all divs inside -> do something on them(change each class to "grass")
or by using a loop.
How to do that?
Please don't use jQuery.
Modern browsers (IE9+):
var divs = document.querySelectorAll('#room div');
[].forEach.call(divs, function(div){
div.className = 'green';
});
var a = document.getElementById("room").getElementsByTagName("div");
for(i = 0; i < a.length; i++)
{
a[i].className = "grass";
}
Do you want to get all divs inside, or just direct children?
This one traverses direct children. If you want to go through all internal nodes, you need to recurse it.
function grassify(nodeId) {
var node = document.getElementById(nodeId);
for(var i in node.childNodes) {
// Do things with node.childNodes[i], for example:
node.childNodes[i].className = 'grass';
}
}
Then just:
grassify('room');
var room=document.getElementByID("#room");
var divs=room.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
doSomething(divs[i]);
}
Use getElementByID and getElementsByTagName
Use getElementsByTagName
First get a reference to the container element, then use getElementsByTagName for the type of element you want.
See http://jsfiddle.net/aQtTx/
JS:
var targetDiv = document.getElementById("div1");
var nestedDivs = document.getElementsByTagName("div");
for(var divIndex = 0; divIndex < nestedDivs.length; divIndex++)
{
nestedDivs[divIndex].style.backgroundColor = 'red';
}
function myFunction()
{
var a=document.getElementById('room').childNodes;
for (i=0; i<a.length; i++)
{
a[i].className="grass";
};
}
JsFiddle
var parent = document.getElementById("room");
var divs = parent.getElementsByTagName('div');
for (i=0; i<divs.length; i++)
{
divs[i].className="grass";
};

Categories