How to add different images in three divs using the same class - javascript

I have this code:
<div class="main_flex">
<div class="flex_items">
</div>
<div class="flex_items">
</div>
<div class="flex_items">
</div>
</div>
javascript:
function shoe_images () {
for (var i = 0; i < shoes.length; i++){
var getFlexItems = document.querySelector('.flex_items');
var createImgTag = document.createElement('img');
createImgTag.src = shoes[i].imageUrl;
getFlexItems.appendChild(createImgTag);
}
};
And i have an array of object with different images. I want to add different images to the
class="flex_items"
How do i do that? I used a for loop, but all the images shows in the first class="flex_items".

The problem is in the querySelector() method. This method return only the first element. It is the reason for this.
See: https://www.w3schools.com/jsref/met_document_queryselector.asp
You need to use querySelectorAll()
See: https://www.w3schools.com/jsref/met_document_queryselectorall.asp
Rewrited your code:
function shoe_images () {
var getFlexItems = document.querySelectorAll('.flex_items');
for (var i = 0; i < shoes.length; i++){
var createImgTag = document.createElement('img');
createImgTag.src = shoes[i].imageUrl;
getFlexItems[i].appendChild(createImgTag);
}

you can do this by css or by js
this for CSS
.flex_items:nth-of-type(2) {
background: #ff0000;
}
.flex_items:nth-of-type(1) {
background: #324445;
}
to used js
var elements = document.getElementsByClassName('flex_items');
it will return arry contain 3 elment [0,1,2]
elements[0].innerHTML ='<img src="path">';
elements[1].innerHTML ='<img src="path">';

You can select the flex_items then append the element image like this:
const images = [{
src: "https://picsum.photos/id/284/200/300"
}, {
src: "https://picsum.photos/id/284/200/300"
}, {
src: "https://picsum.photos/id/284/200/300"
}]
document.querySelectorAll(".flex_items").forEach((el, index) => {
const image = document.createElement("img");
image.setAttribute("src", images[index].src);
el.appendChild(image);
})
<div class="main_flex">
<div class="flex_items">
</div>
<div class="flex_items">
</div>
<div class="flex_items">
</div>
</div>

Related

Creating parent and child elements wit Js/jQuery

I'm beginner at js/jquery.
I want to code this structure with js/jquery:
<div class="box">
<p>1</p>
<div class="content"><span>Lorem</span></div>
</div>
<div class="box">
<p>2</p>
<div class="content"><span>Ipsum</span></div>
</div>
<div class="box">
<p>3</p>
<div class="content"><span>Dolor</span></div>
</div>
<div class="box">
<p>4</p>
<div class="content"><span>Sit</span></div>
</div>
<div class="box">
<p>5</p>
<div class="content"><span>Amet</span></div>
</div>
I have this code:
function addDivs(n) {
for(var i=1; i<=n; i++) {
var parentP = $("<p>"+i+"</p>");
var parentContent = $("<div class='content'></div>");
var boxClassDiv = document.createElement("div");
document.body.appendChild(boxClassDiv);
boxClassDiv.setAttribute("class", "box");
$("body").prepend(boxClassDiv, [parentP, parentContent]);
}
}
window.onload = function getFuncs() {
addDivs(16);
}
Here is fiddle: https://jsfiddle.net/ds6wj38k/2/
I found a few similar questions like this and tried to add to my code but i can't adjust.
Thanks.
So first of all you need a div with class box:
var box = $('<div>').addClass('box');
Then you want a p with a number:
var p = $('<p>').text(1);
And finally a div with class content and span inside:
var content = $('<div>').addClass('content');
var span = $('<span>').text('any');
content.append(span);
So you created elements you need. Time to combine them:
var listItem = box.append(p).append(content);
And add to body!
$('body').append(listItem);
The final code:
function addDivs(n) {
for (var i = 1; i <= n; i++) {
var box = $('<div>').addClass('box');
var p = $('<p>').text(i);
var content = $('<div>').addClass('content');
var span = $('<span>').text('any');
content.append(span);
var listItem = box.append(p).append(content);
$('body').append(listItem);
}
}
window.onload = function getFuncs() {
addDivs(16);
}
Check out code online: http://jsbin.com/xeyugubefu/edit?js,output
Here is how I would suggest to do it:
function addDivs(words) {
words.forEach( function (word, i) {
$('body')
.append($('<div>').addClass('box')
.append($('<p>').text(i+1))
.append($("<div>").addClass('content').append($('<span>').text(words[i]))));
});
};
$(function getFuncs() {
var words = 'Lorem ipsum dolor sit amet'.split(' ');
addDivs(words);
});
jQuery is designed to support method chaining, which the above code demonstrates.
Note that apart from building the content with jQuery, you should also replace window.onload with a jQuery.ready call, which you can write as $(callback).

How to reference elements without assigning Id's?

So, the following works - but can I replace the references 'img11', 'name11' and 'prof11' with something like 'this' so I don't have to assign id's every time I use this code?
<div onclick="changeStored(img11); changeName(name11); changeProf(prof11) ">
<div style="float:left">
<img id="img11" style="max-height:80px;" src="Pictures/Smiley.png">
</div>
<div style="float:left;">
<p id="name11">Name: Jane Doe</p>
<p id="prof11">Profession: Something</p>
</div>
</div>
I will post the functions just for completeness:
function changeStored(img){
storeOnClick = img.src;
alert(storeOnClick);
}
function changeName(img){
name = document.getElementById("name11").innerHTML;
alert(name);
}
function changeProf(img){
prof = document.getElementById("prof11").innerHTML;
alert(prof);
}
And no I can't just put the onclick event in the img or p because I need all 3 values to pass back to the functions when the user clicks anywhere in the div.
I think you can do something like this:
html
<div class="info">
<div style="float:left">
<img class="myimg" style="max-height:80px;" src="Pictures/Smiley.png">
</div>
<div style="float:left;">
<p class="myname">Name: Jane Doe</p>
<p class="myprof">Profession: Something</p>
</div>
</div>
js
var _divs = document.querySelectorAll('.info');
function changeAll() {
for (var i = 0; i < _divs.length; i++) {
var myimg = _divs[i].querySelector('.myimg'),
myname = _divs[i].querySelector('.myname'),
myprof = _divs[i].querySelector('.myprof')
// img
var storeOnClick = myimg.src;
alert(storeOnClick);
// name
var name = myname.innerHTML;
alert(name);
// profession
var prof = myprof.innerHTML;
alert(prof);
}
}
EDIT
To make this happen on 'click':
window.onload = function () {
var _divs = document.querySelectorAll('.info');
for (var i = 0; i < _divs.length; i++) {
_divs[i].addEventListener("click", function () { changeInfo(this) }, false);
}
}
function changeInfo(el) {
var myimg = el.querySelector('.myimg'),
myname = el.querySelector('.myname'),
myprof = el.querySelector('.myprof')
// img
var storeOnClick = myimg.src;
alert(storeOnClick);
// name
var name = myname.innerHTML;
alert(name);
// profession
var prof = myprof.innerHTML;
alert(prof);
}
You could still use the changeAll() if you wanted to do this for all info divs on page..
of course run your js after html has loaded..

container hasChildNodes() showing null value. Why

<div id="history">
<div id="histheading" class="pull-left">History</div>
<div id='hist'><canvas id="test"></canvas></div>
</div>
var left=100;
var t=-150;
function doHistory_double()
{
var data = localStorage.getItem('HTML5TTT');
data = JSON.parse(data);
data.reverse();
var container = document.getElementById('hist');
// Clear the container
while (container.hasChildNodes())
{
container.removeChild(container.firstChild);
}
// Loop through the data
canvID = 0;
for(x in data)
{
var i=1;
var hist = data[x];
if(hist.datetime == undefined)
break;
var elem = document.createElement('div');
elem.style.marginLeft=lef + "px";
if(i==1){
elem.style.marginTop=t + "px";
}
else
elem.style.marginTop="0px";
i++;
elem.innerHTML = "<p><strong>"+hist.datetime+"</strong><br>Winner: "+hist.winner+"<br><canvas id='can"+canvID+"' width='100px' height='100px' ></canvas>";
container.appendChild(elem);
drawMiniBoard_double(document.getElementById("can"+canvID),hist.board);
canvID++;
lef+=310;
}
}
This is my javscript code. hist is a div showing history of the game.I am getting error as Cannot call method 'hasChildNodes' of null.I am getting this error after i did something using the variable left and t i.e margin-top and margin-left. Help me to solve this.
write it in a function and call it onload of document.
function deleteChildren() {
var container = document.getElementById('hist');
// Clear the container
while (container.hasChildNodes())
{
container.removeChild(container.firstChild);
}
}
<body onload="deleteChildren()">
<div id="history">
<div id="histheading" class="pull-left">History</div>
<div id='hist'><canvas id="test"></canvas></div>
</div>
</body>
its working perfectly.. check the fiddle
I have bind the click method then calling the code you provided and alert to show either we got a child inside the container or not..
--HTML--
<div id="history">
<div id="histheading" class="pull-left">History</div>
<div id='hist' onclick=f()><canvas id="test"></canvas></div>
</div>
-- JS --
function f()
{
var container = document.getElementById('hist');
// Clear the container
alert(container.hasChildNodes());
while (container.hasChildNodes())
{
container.removeChild(container.firstChild);
}
}
http://jsfiddle.net/FLC3R/

How to create a clickable list of divs with sub items using JavaScript

I want to create a list of clickable divs from arrays using Javascript, where the list structure has to be something like this:-
<div id="outerContainer">
<div id="listContainer">
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
<div id="listElement">
<div id="itemId"> </div>
<div id="itemTitle"> </div>
<div id="itemStatus"> </div>
</div>
</div>
</div>
I want to extract the values of itemId, itemTitle and itemStatus from three arrays itemIdData[ ], itemTitleData[ ] and itemStatusData[ ] respectively, to create the whole list.
Also, when I click on any of the listElements, I want an alert showing the itemId. Can anyone help me with this problem.
If you're using jQuery, then try something like this:
$("#listContainer").on("click", "div", function () {
console.log("jQuery Event Delegation");
alert($(this).find(">:first-child").attr("id"));
});
It's possible to write the same thing without jQuery, but will take further lines of code - I'm conveying the idea of delegation here (there are extensive existing docs and examples on the JQuery site, and here on this site).
NB: the code you're submitted in the question can't(shouldn't) have multiple DOM elements with same IDs (that's what classes are for - for semantically similar elements). Also, trying to emulate a list using divs instead of li elements is perhaps not best practice.
After a bit of experimentation, understood what I was doing wrong and how to get it done.
Here's the code:-
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
for (var i = 0; i < json.length; i++) {
//create the element container and attach it to listContainer.
var listElement = document.createElement("div");
listElement.id = i;
listElement.className = "listItemContainer";
listElement.addEventListener("click", function(e){
var itemId = e.target.children[1].innerHTML;
alert(itemId);
});
listContainer.appendChild(listElement);
//create and attach the subchilds for listElement.
var itemTitle = document.createElement("span");
itemTitle.innerHTML = postTitleData[i];
itemTitle.id = 'title'+i;
itemTitle.className = "itemTitle";
listElement.appendChild(itemTitle);
var itemId = document.createElement("div");
itemId.innerHTML = postIdData[i];
itemId.id = 'id'+i;
itemId.className = "itemId";
listElement.appendChild(itemId);
var itemStatus = document.createElement("span");
itemStatus.innerHTML = postStatusData[i];
itemStatus.id = 'status'+i;
itemStatus.className = "itemStatus";
listElement.appendChild(itemStatus);
}
Tried something like this which isn't quite working!
var listContainer = document.createElement("div");
document.getElementById("outerContainer").appendChild(listContainer);
var listElement = document.createElement("div");
listContainer.appendChild(listElement);
listElement.className = "listItemContainer";
for (var i = 0; i < json.length; i++) {
var itemId = document.createElement("div");
itemId.innerHTML = idData[i];
listElement.appendChild(itemId);
itemId.className = "itemId";
var itemTitle = document.createElement("div");
itemTitle.innerHTML = titleData[i];
listElement.appendChild(itemTitle);
itemTitle.className = "itemTitle";
var itemStatus = document.createElement("div");
itemStatus.innerHTML = statusData[i];
listElement.appendChild(itemStatus);
itemStatus.className = "itemStatus";
listElement.appendChild(document.createElement("hr"));
var elementId = 'ListElement'+i;
listElement.id = elementId;
listElement.addEventListener("click", function(){
alert(document.getElementById(elementId).innerHTML);
});
}

Appending ascending images based on the id of parent div

Say I had the following three divs with unique ids on a page
<div id="product-id-001"></div>
<div id="product-id-002"></div>
<div id="product-id-003"></div>
What code would I need to add the following image elements based on the id of the div?
<div id="product-id-001">
<img src="images/product-id-001-1.jpg"></img>
<img src="images/product-id-001-2.jpg"></img>
<img src="images/product-id-001-3.jpg"></img>
</div>
<div id="product-id-002">
<img src="images/product-id-002-1.jpg"></img>
<img src="images/product-id-002-2.jpg"></img>
<img src="images/product-id-002-3.jpg"></img>
</div>
<div id="product-id-003">
<img src="images/product-id-003-1.jpg"></img>
<img src="images/product-id-003-2.jpg"></img>
<img src="images/product-id-003-3.jpg"></img>
</div>
Thanks for any tips.
$('div[id^=product]').each(function(index, elem) {
for(var i = 1; i < 4; i++) {
$('<img>', {
src: '/images/' + elem.id + i
}).appendTo(this);
}
});
Demo: http://www.jsfiddle.net/9S9Av/
(You need Firebug or another DOM inspector to see the result)
From the jQuery docs:
"The .append() method inserts the specified content as the last child of each element in the jQuery collection"
So:
$('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
etc...
// Select all elements with an id beginning with product-id:
var $productContainers = $('[id^=product-id]');
// Loop through the matched elements and append the images:
$productContainers.each(function () {
var $this = $(this),
productId = $this.attr('id'),
numImages = 3,
extension = '.jpg';
// Create and append the images based on the configuration above. Note that this
// assumes that each product have three valid images.
for (var i = 1; i <= numImages; i++)
{
var $image = $('<img alt="" />').attr('src', 'images/'+productId+'-'+i+extension);
$image.appendTo($this);
}
});

Categories

Resources