Add html content to js generated class - javascript

I have a trivial issue and need your help. Thanks to you, I have 2690 squares generated by js:
var i, square, text, container = document.getElementById("square_container");
for (i = 1; i <= 2690; i += 1) {
square = document.createElement("div");
square.id = "square" + i;
square.classList.add("square");
text = document.createElement("h1");
text.innerHTML = i;
text.id = "text" + i;
square.appendChild(text);
container.appendChild(square);
text.classList.add("hover");
}
The code above generate 2690 of this:
<div id="square1" class="square"><h1 id="text1">1</h1></div>
And now, I need to add following html content to each .square class:
<div class="hover">Click Me</div>
So in the result I need to have:
<div id="square1" class="square"><h1 id="text1">1</h1>
<div class="hover">Click Me
</div>
</div>
https://fiddle.jshell.net/tynw5c34/3/
I tried .append, .addClass...but it doesn't work. Thank you in advance for your help!

Here is another solution:
for (i = 1; i <= 2690; i += 1) {
square = document.createElement("div");
square.id = "square" + i;
square.classList.add("square");
text = document.createElement("h1");
text.innerHTML = i;
text.id = "text" + i;
square.appendChild(text);
container.appendChild(square);
$('#square'+i).append('<div class="hover">Click Me</div>');
}
If you want generate squares with Javascript, use this :
var i, square, text, container = document.getElementById("square_container");
var content = document.createElement('div');
content.className = 'hover';
var a=document.createElement('a');
a.href='#';
a.innerHTML='Click Me';
content.appendChild(a);
for (i = 1; i <= 2690; i += 1) {
square = document.createElement("div");
square.id = "square" + i;
square.classList.add("square");
text = document.createElement("h1");
text.innerHTML = i;
text.id = "text" + i;
square.appendChild(text);
container.appendChild(square);
document.getElementById('square'+i).appendChild(content.cloneNode(true));
}
You need to use cloneNode() method , which clones all attributes and values of specified element. A node can't be in two locations in the tree at once.
Here is a working solution: jsfiddle

Lukas. To achieve the function you were looking for using jQuery, I added an external resource:
https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js
and added this to the javascript:
$( ".square" ).append("<div class=\"hover\">Click Me</div>")
I hope this helps.

You can append the html in pure javascript like this
var squares = document.getElementsByClassName("square");
var str = '<div class="hover">Click Me </div>';
Array.prototype.forEach.call(squares, function(sqr, index)
{
sqr.innerHTML = sqr.innerHTML + str;
});
Working fiddle : https://fiddle.jshell.net/egxbhehu/

The append function should work.
Also, please note that <h1></h1> tag should be used only once per page. Consider using <span></span> and CSS to make it look like your current h1 tag.

You should use createDocumentFragment() to append multiple childs.
var i, square, text, hoverDiv, aHref, container = document.getElementById("square_container");
for (i = 1; i <= 4; i += 1) {
square = document.createElement("div");
square.id = "square" + i;
square.classList.add("square");
text = document.createElement("h1");
text.innerHTML = i;
text.id = "text" + i;
hoverDiv = document.createElement("div");
hoverDiv.classList.add("hover");
aHref = document.createElement("a");
aHref.href = "#";
aHref.innerHTML = "Click Me";
hoverDiv.appendChild(aHref);
var docFrag = document.createDocumentFragment();
docFrag.appendChild(text);
docFrag.appendChild(hoverDiv);
square.appendChild(docFrag);
container.appendChild(square);
}

Related

problems with appendChild <LI> and having Images match <LI> element

I would like to have 3 li elements and in those li elements I want 1 image.
All the images go into the first li element instead of being spread out.
Any suggestion would be greatly appreciated...
I have tried this but it does not work..
/////////////CODE///////////////////
var node = document.createElement("LI");
node.innerHTML =
"<ul class= rsox style=list-style-type: none>" +
"<li class=images id=imageList>" +
"</li>" +
"</ul>";
document.getElementById('sele').appendChild(node);
var image = { image1.jpg, image2.jpg, image3.jpg };
for (i = 0; i < image.length; i++) {
container = document.getElementById ("imageList");
container.innerHTML += "<img class= imageClass src=https://www.WEB-SITE-NAME.com/" + image[i] + ">"
}
Your code is really not clean and I think I know what you want to achieve, so here's my try in fixing your code:
var images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var node = document.createElement("li"};
node.className = "rsox" ;
node.style.listStyleType = "none";
for (var i = 0; i < images.length; i++) {
var listItem = document.createElement("li");
listItem.className = "images";
var img = document.createElement("img");
img.className = "imageClass";
img.alt = "";
img.src = "https://www.WEB-SITE-NAME.com/" + images[i];
listItem.appendChild(img);
node.appendChild(listItem);
}
document.getElementById("sele").appendChild(node);
I haven't tested this, so if you get any errors or something, tell me.

How to give unique ids to each child div created dynamically?

The function displays eight elements on click in dynamically created divs using the slice() method. How can I give a unique id to each div? Your suggestions would be of great help to me.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++) {
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
}
I have tried this but it's not working:
var mainDiv = document.getElementById('container');
var first = mainDiv.getElementsByTagName('div')[0];
first.id = 'one';
You can do it right inside the for loop while it's iterating:
for (i = 0; i < newArray.length; i++)
{
x += '<div id="box-' + i + '"> class="box">' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
You can use assign an ID inside the text string.
Here are a couple of other things you can do to improve this code:
Move the getElementById outside the loop
use js methods instead of string concatenation
Something like this (untested):
// get the container
container = document.getElementById('container');
for (i = 0; i < newArray.length; i++)
{
// create a div
var div = document.createElement('div');
// add attributes
div.setAttribute("id", "box-" + i);
div.setAttribute("class", "box");
// create text node
var textnode = document.createTextNode("This is div #" + i);
// add text to div
div.appendChild(textnode);
// append to container
container.appendChild(div);
}
How about giving it the id when creating? Also put the class=box in quotations like so -> class="box".
And add the whole div construct only once after the for loop. Because right now you are basically overwriting the whole thing multiple times.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
// Change class and add custom id
x += '<div class="box" id="box-'+i+'">' + newArray[i] + '</div>';
}
document.getElementById('container').innerHTML = x; // Add divs after for loop
x = "";
count += 8;
}
Now each box has a unique id going from box-0, box-1, ... to box-n

createElement or appendChild not working

I am trying to put an img element in a span element that I created dynamically with JavaScript. The problem is that the span element isn't showing in the DOM tree. However, the img elements are shown on the page and are nested in the div element (#playfield) that is hard coded in my html code. I really don't know what I'm doing wrong.
var playfield = document.getElementById("playfield");
var indexes = [0,1,2,3,4,5,6,7,8,9,10,11];
shuffle(indexes);
for (var i = 0; i < 12; i++) {
var vak1 = document.createElement("span");
var kaart1 = document.createElement("img");
var path1 = "img/kaart" + indexes[i] + ".png";
var klasse1 = "img" + indexes[i];
kaart1.setAttribute("src", "img/achterkant.png");
kaart1.setAttribute("class", klasse1);
kaart1.setAttribute("data-img", path1);
kaart1.setAttribute("height", "150");
kaart1.setAttribute("width", "150");
kaart1.setAttribute("data-turned","false");
playfield.appendChild(vak1.appendChild(kaart1));
}
playfield.appendChild(vak1.appendChild(kaart1)); Is the problem line. The result of vak1.appendChild(kaart1) is the appended child kaart1 - do these 2 operation separately:
vak1.appendChild(kaart1);
playfield.appendChild(vak1);
var playfield = document.getElementById("playfield");
var indexes = [0,1,2,3,4,5,6,7,8,9,10,11];
for (var i = 0; i < 12; i++) {
var vak1 = document.createElement("span");
var kaart1 = document.createElement("img");
var path1 = "img/kaart" + indexes[i] + ".png";
var klasse1 = "img" + indexes[i];
//kaart1.setAttribute("src", "img/achterkant.png");
kaart1.setAttribute("class", klasse1);
kaart1.setAttribute("data-img", path1);
kaart1.setAttribute("height", "150");
kaart1.setAttribute("width", "150");
kaart1.setAttribute("data-turned","false");
vak1.appendChild(kaart1)
playfield.appendChild(vak1);
}
Append to the first and then add that to the playfield.
You're adding the created <img> as a child to #playfield. If you want it in a <span>, you'll have to add it to the <span> and then add that <span> to #playfield.

I want to create div's in javascript so I do not have to sit there and make a hundred different divs

Okay so instead of typing out a hundred div tags in the hmtl I would like to generate them in javascript and have them show on the page. Here is what I have, but it will not work.
var arry = {};
for(var i = 0; i<100; i++){
arry[i] = i;
}
for each (var x in arry){
var div = document.createElement('div');
div.id = x;
document.getElementById('body').appendChild(div);
}
body is not an id, it is a tag. you need
document.getElementsByTagName('body')[0].appendChild(div);
This will create one hundred divs, each with a text node inside containing the number of the div.
var body = document.querySelector('body');
for(var x = 0; x < 100; x++) {
var div = document.createElement("div");
var text = document.createTextNode(x);
div.appendChild(text);
body.appendChild(div);
}
Alternatively you can do this:
var divs = '';
for (var i = 1; i <= 100; i++) {
divs += '<div id="id_' + i + '">Div ' + i + '</div>';
}
document.write(divs);

Javascript regex classname issue

Apologies for the vague title of this question!
I have the following JS, it looks for img tags with images of certain sources. It then replaces the img tag with a span so that I can replace the images/icons with iconfonts.
var paths = [
"folder%2Fadd",
"folder%2Fclear",
"folder%2Fdelete",
"folder%2Fedit",
"folder%2Fmove",
"folder%2Fsort",
];
var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);
for (var i = 0; i < imgs.length; i++) {
var span = document.createElement("span");
span.addClass("iconfont");
span.title = imgs[i].parentNode.title;
imgs[i].parentNode.replaceChild(span, imgs[i]);
}
Everything is working nicely so far, but there is one more issue that I cannot solve.
Apart from adding a class to the span of .iconfont, I also want to add two more classes to the span - 1) the original class of the replaced img element, and 2) the name of the image source as in my array, but without the 'folder/' bit in front.
So, at the moment I have:
<img class = "tinyicon" src="******/t/edit">
and my script creates this in the DOM:
<span class = "iconfont">
But I want my script to create the following:
<span class = "iconfont tinyicon edit">
That is what I am after :)
Thanks for having a look!
var paths = [
"folder%2Fadd",
"folder%2Fclear",
"folder%2Fdelete",
"folder%2Fedit",
"folder%2Fmove",
"folder%2Fsort",
];
var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i],
iClass = img.className,
iSrc = img.src.split('/').pop(),
span = $('<span />', {'class': 'iconfont '+iClass+' '+iSrc,
title : img.parentNode.title
});
$(img).replaceWith(span);
}
Change this:
var span = document.createElement("span");
span.addClass("iconfont");
to this:
var span = document.createElement("span");
span.className = "iconfont tinyicon edit";
Your addClass() wouldn't work anyway because span is a DOM node, not a jQuery object.
var span = document.createElement("span");
var className = "iconfont " + imgs[i].className + ' ' + imgs[i].src.match(/([a-z])$/i, '')
span.className = className ;
span.title = imgs[i].parentNode.title;
imgs[i].parentNode.replaceChild(span, imgs[i]);

Categories

Resources