Loop and array issue - javascript

Ok, I have a literal arrays where there are some images in it. I have an empty DIV where a FOR LOOP will be carried out to display all the images in the array in the div.
var icons = [
'<img src="images/1.png" width="30" height="30"/>',
'<img src="images/2.png" width="30" height="30"/>',
'<img src="images/3.png" width="30" height="30"/>'
];
var lol = document.getElementById("div");
for (var i=0; i<icons.length; i++) {
lol.innerHTML = icons[i] ;
}
The issue is only the last image is displayed not all...

That is because you are overwriting the previous image with the current one. If you want to append/concat all images, use +=:
lol.innerHTML += icons[i];
A better way to handle this would be to use DOM handling:
var img = document.createElement("img");
img.setAttribute("src", icons[i]);
lol.appendChild(img);

Each time you do
lol.innerHTML = icons[i];
you're replacing the inner HTML of the div with icons[i]. Concatenate all your icon elements, and then set the inner HTML of the div with the result of the concatenation.

your code is overwrite the innerHTML you can append the innerHTML
try this
lol.innerHTML += icons[i];
this above code is append the innerHTML
or in jquery you can use append function
$('#div').append(icons[i]);

Related

How can I set src and alt attributes on an image tag using JavaScript

JavaScript is something that I am learning bit by bit, so please excuse my ignorance...!
I have a list of images in a gallery, and I am creating a modal on a click event. I have managed to collect all of the sources for the images into an array and have then used the forEach method to appended an li and img tag into a parent ul, with all of the sources going into the src attribute.
My problem is I also have an array of alt attributes as well that I also need to set into the same list of images.
I don't think I can do both attributes in one forEach loop, and it seems too messy to do a second loop for the alt attributes. There must be a simpler way, it's just beyond my current understanding.
Here is the code I already have below, I was wondering if perhaps I should be looking at a JSON object instead rather than this approach?
$('.gallery-image img').click(function(){
$('.modal').addClass('show');
var images = document.getElementsByClassName('aurora-gallery-image');
var imageSources = [];
var imageTitles = [];
for (var i = 0; i < images.length; i++) {
imageSources.push(images[i].src);
imageTitles.push(images[i].alt);
}
imageSources.forEach(imageFunction);
function imageFunction(item){
$('.image-modal ul').append('<li class="image-modal-item"><img class="modal-content" alt="" src="' + item + '" /><p id="aurora-gallery-image-title"> </p></li>');
}
});
forEach() passes the array index as the second argument to the callback function. You can use that to get the corresponding element from the imageTitles array
function imageFunction(item, index){
$('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${imageTitles[i]}" src="${item}" /><p id="aurora-gallery-image-title"> </p></li>`);
}
But you don't really need the arrays at all. Just do it in the for loop:
for (let i = 0; i < images.length; i++) {
$('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${images[i].alt}" src="${images[i].src}" /><p id="aurora-gallery-image-title"> </p></li>`);
}

Is there any way I can make 200 similar divs with different files (page0.svg, page1.svg..., page200.svg)

<div class="mySlides">
<img src="1173/page0.svg" style="width:50%">
</div>
<div class="mySlides">
<img src="1173/page1.svg" style="width:50%">
</div>
So I need to make about 200 div codes like the above with different .svg files, and the only thing that changes in the file name is the number. I'm trying to create a digital book, and I have all the pages in .svg format.
Sure, there are lots of different ways to do this. As suggested above you can use a fragment to give you better performance than adding 200 divs to the DOM sequentially.
var fragment = document.createDocumentFragment();
for(i=0;i<200;i++){
var new_div = document.createElement("div");
new_div.classList.add("mySlides");
new_div.innerHTML += '<img src="1173/page'+i+'.svg" style="width:50%">';
fragment.appendChild(new_div);
}
document.body.appendChild(fragment);
See it running here: https://codepen.io/67hours/pen/gBMygW
In pure JS, you could write something like this. Using document.createElement and then appending the new elements to the parent container is a far superior approach to manipulating the DOM than that of HTML string manipulation/concatenation with elements' innerHTML attributes.
Substitute the hard-coded loop limit for a variable representing the actual number (assumes as well you have a 0.svg):
var IMAGE_COUNT = 200;
for (var i = 0; i < IMAGE_COUNT; i++) {
var frag = document.createElement("div");
var img = document.createElement("img");
frag.classList.add('mySlides');
frag.style = "width:50%;";
img.src = '1173/page/' + i + '.svg';
frag.appendChild(img);
document.body.appendChild(frag);
}
Use for loop upto 200 and generate html dynamcally and append that to parent div
var container = document.getElementById("container");
var html = "";
for(var i=0;i<=200; i++)
{
html += "<div class='mySlides'><img src='1173/page"+i+".svg' style='width:50%'></div>";
}
conatiner.innerHTML = html;
HTML
<div id="container">
</div>

Write a <img> element inside of a <li> element with Javascript

I've been working with Javascript for a little bit now. My code below has various pictures defined as an object. Now I want to put these images as <img> inside <li> tags. However, I am experiencing some difficulty with this.
for (var i = 0; i < pictures.length; i++){
var newImage = document.createElement('img')
newImage.setAttribute('class', 'image-item')
newImage.setAttribute('alt', pictures[i].name)
newImage.src = pictures[i].url
var liItem = document.createElement('li')
liItem.innerHTML = newImage
document.getElementById('pictures').appendChild(liItem)
console.log(liItem)
}
Any idea on how to resolve this? The result has to look like this:
<li><img src="picture1.jpg" alt="loremipsum"></li>
Right now console tells me the following:
Change liItem.innerHTML = newImage to liItem.appendChild(newImage)
The innerHTML property sets or returns the HTML content (inner HTML) of an element. so you should change liItem.innerHTML = newImage to liItem.appendChild(newImage)

add different background-image to elements from json array

Everything is working, but when I want to add background-image, to different elements, it's just putting last image from array, and set css backgorund to all of them with that last image.
$.get('con.php',function(data) {
var data = JSON.parse(data);
for(i = 0; i < data.length; i++) {
var div = "<div class='nemkec-dev' id='"+data[i].id+"'>"+"<h1>"+ data[i].text+"</h1>"+"<p>"+
data[i].text2+"</p>"+"<img src='images/"+data[i].image+"'/>"+"</div>";
$('body').append(div);
var image = data[i].image;
}
$.each(data, function(i, dat) {
$('.nemkec-dev').css('background-image','url(images/'+dat.image+')');
});
It shows image as element. But, when I want to set css rule it's not working.
Just appending last-image to all for background.
When creating var div you can create an inline style var div = "<div style='background-image: url(images/"+data[i].image+")'...
I am pretty sure you want to iterate over $('.nemkec-dev') elements. What you are doing now is iterating over background images and setting background image for all of .namkec-dev divs at once. So natural outcome is that after this script ends you have all .nemkec-dev elements with the last background image.
You can go with Michael Coker solution and use them in line with other variables, or do something like this:
var i = 0;
$('.nemkec-dev').each(function() {
$(this).css('background-image', data[i].image);
i++;
});

Need Regular expression javascript to get all images

I have string that contains html . The html has several img tags in it . I want to find all the img tags and have some kind of collection so that i can replace them with my code.
Does anybody has any idea.
I want it in Javascript
var html_str = '...some images and other markup...';
var temp = document.createElement( 'div' );
temp.innerHTML = html_str;
var images = temp.getElementsByTagName( 'img' );
...then loop over the images...
for( var i = 0; i < images.length; i++ ) {
images[ i ].className = "my_class";
}
What you actually need to do may change how your loop runs, but the above just adds a class, so it is just a normal for loop.
Note that at this point you're dealing with DOM elements, not markup. These elements can be added directly to the DOM.
If you used jQuery you could do something like:
var html = '<div><img src="bla" /></div>';
$(html).find('img');
If you want to replace all images you would do:
var html = '<div><img src="bla" /></div>';
$(html).find('img').replaceWith('<div>Image was here</div>');
This is regex pattern to take all image tag:
var pattern = /\<img .+?\/\>/ig;
UPDATE: sample is here http://jsbin.com/oxafab/edit#source

Categories