Calling <img src > tag in loop - javascript

I want to display all images in a array on my web page. Can I call img tag in a loop? Or if anyone could suggest a way to print all images with source urls in a array will be very helpful?
<div id="wrapper"></div>
<script>
var container = document.getElementById("wrapper");
function myFunction() {
var index;
var urls = ["Banana.jpg", "Orange.jpg", "Apple.png", "Mango.jpg"];
for (index = 0; index < urls.length; index++) {
var newImage = '<img src="+url[index]+" alt="#" /> ' + index;
container.innerHTML += newImage;
}
}
</script>
PS: I'm newbie in JS

You really shouldn't use the innerHTML += method. Use the insertAdjacentHTML() method instead.
var container = document.getElementById("wrapper");
var urls = ["Banana.jpg", "Orange.jpg", "Apple.png", "Mango.jpg"];
for( i=0; i<urls.length; i++){
container.insertAdjacentHTML('beforeend', '<img src="'+urls[i]+'">');
}
<div id="wrapper"></div>
PS, if you are going to wrap this code inside a function. Remember to call the function.

First of all your syntax for building the img tags are wrong, notice below that the array isn't par of the string literal but concatenated to it.
'<img src="'+url[index]+'" alt="#" /> '
Also I would build the html first, then add it to the div.
var newImages = '';
for (index = 0; index < urls.length; index++) {
newImages += '<img src="'+url[index]+'" alt="#" /> ' + index;
}
container.innerHTML += newImages;

Related

create multiple divs using a for loop

This is a really simple question but I don't know why it doesn't work.
I have an array with 3 items inside. And I have a container which I would like to insert a number of divs based on the number of items in my array. I used a for loop for this but it is only creating one div. Should it not create 3?
for (var i = 0; i < array.length; i++) {
var container = document.getElementById("container");
container.innerHTML = '<div class="box"></div>';
}
here is a fiddle to demonstrate further fiddle
Move container out of the loop, it is not required inside it.
Append the innerHTML in each iteration.
var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
container.innerHTML += '<div class="box"></div>';
}
Edit:
Thanks Canon, for your comments. I also wanted to suggest the same approach as yours, but I got busy in some other work after posting the answer [No excuses :)] Updating the answer:
var htmlElements = "";
for (var i = 0; i < array.length; i++) {
htmlElements += '<div class="box"></div>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
This may look like involving more lines of code but this will be more efficient and less error-prone than the previous solution.
Replace = to +=
As per the #canon comment, edited answer are below
var innerHTMLString = "";
forloop {
innerHTMLString += '<div class="box"></div>';
}
document.getElementById("htmlElements").innerHTML = innerHTMLString
Replace this
container.innerHTML = '<div class="box"></div>';
with this
container.innerHTML += '<div class="box"></div>';
If you want to create more than one, you must call createElement more than once.
d=document.createElement("div");
line into the j loop.
If you call appendChild passing in an element that's already in the DOM, it's moved, not copied.
window.onload=function()
{
var i=0;
var j=0;
for (i=1; i<=8; i++)
{
for (j=1; j<=8; j++)
{
if ((i%2!=0 && j%2==0)||(i%2==0 && j%2!=0))
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="black";
}
else
{
var d=document.createElement("div");
document.body.appendChild(d);
d.className="white";
}
}
}
}
Javascript Method -
var container = document.getElementById("container");
for (var i = 0; i < array.length; i++) {
container.innerHTML += '<div class="box"></div>';
}
jQuery Method -
foreach(array as value){
$("#container").append('<div class="box"></div>')
}
For further references; what about this approach? :)
HTML:
<div class="particles">
<div class="parts"></div>
</div>
JavaScript:
// Cloning divs where particles go in order not to put 300 of them in the markup :)
const node = document.querySelector(".parts");
[...Array(300)].forEach(_ =>
node.parentNode.insertBefore(node.cloneNode(true), node)
);

Modal doesn't work

I made a modal using jQuery, but it doesn't seem to work properly. I'm calling my images in a javascript function, and the modal is in my window.onload in the same page the images are loaded. I'm loading the images first, but the modal only works if i put the imgs directly in the HTML and if i take everything else from the window.onload. That's how i'm calling all imgs:
function maisGaleria(n){
var galeria = new Array();
var img = document.querySelector("#gallery");
var pic = 0;
if(n == 1){
pic = 4;
}else if(n == 2){
pic = 7;
}else{
pic = 4;
}
img.innerHTML = "<div class='row'>";
img.innerHTML += "<div class='six columns'>";
img.innerHTML += "<h4>Galeria "+n+"</h4>";
for(var i = 0; i < pic; i++){
galeria[i] = "foto"+n+"_"+(i+1)+".jpg";
}
for(var i = 0; i < galeria.length; i++){
img.innerHTML += "<img src='img/"+galeria[i]+"' class='imgs-modal'>";
}
img.innerHTML += "</div>";
img.innerHTML += "</div>";
}
and the window.onload with the modal:
window.onload = function(){
var rdSocial = document.querySelector("#social");
var teste = document.querySelector("#teste");
var fb = '<img src="img/fb.png" value="1" class="img" onclick="redireciona(this);">';
var twt = '<img src="img/twitter.png" value="2" class="img" onclick="redireciona(this);">';
var insta = '<img src="img/insta.png" value="3" class="img" onclick="redireciona(this);">';
rdSocial.innerHTML += fb;
rdSocial.innerHTML += twt;
rdSocial.innerHTML += insta;
var x = location.search.split("?gal=")[1];
y = document.querySelector("#pics");
//console.log(x);
y.onload = maisGaleria(x);
//the modal starts here
$('.imgs-modal').on('click', function(){
var obj = $(this).clone();
console.log(obj);
$("#box_modal").html(obj);
$("#modal").fadeIn(1000);
});
$(".fechar").on('click', function(){
$("#modal").fadeOut(1000);
});
}
#anuseranother there are few errors in you code.
Before calling maisGaleria method in window.onload, you have to declare/define it.
As per your jsfiddle, it is throwing errors like maisGaleria is not defined. So define maisGaleria it before using it.
After fixing this error, another error is "Cannot set property 'onload' of null". There is no #pics element in the dom (y = document.querySelector("#pics")) and you are referencing it and adding onload method to it. Please update these two and let us know exactly how you need a modal with images any example in internet.

JavaScript increment images

I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg

How to get all img and its attributes?

`
<ul class="flickr-badge-content">
<li class="first">
<img data-photo-attribution="andysouthwales" data-photo-page="http://www.flickr.com/photos/andysouthwales/1212121/" data-photo-title="abcd" data-photo-id="1212121" src="http://farm3.static.flickr.com/2855/1212121_ce6bfd5c38_s.jpg"></img>
</li>
<li>
<img data-photo-attribution="andysouthwales" data-photo-page="http://www.flickr.com/photos/andysouthwales/1263324993173/" data-photo-title="tennn" data-photo-id="1263324993173" src="http://farm8.static.flickr.com/7457/1263324993173_0e3e9745f8_s.jpg"></img>
</li>
<li>..............</ul>.......
I want to get all image and their attributes. Please Help...
You can cycle through all of the images attributes by using
$('img').each(function(currentImage){
console.log(currentImage.data('photo-attribution')); //log some attribute
});
I'm sure that you will figure the rest out.
I have provided you an example which selects all the image tag and gets the source attribute of each of them. You can use this to get whichever attribute you want.
Using JavaScript
var images = document.getElementsByTagName('img');
var srcList = [];//This is just for the src attribute
for(var i = 0; i < images.length; i++) {
srcList.push(images[i].src);
}
Instead of document.getElementsByTagName('img') you could also use the document.images collection.
function allSrc() {
var src = [];
var imgs = document.images;
for (var i=0, iLen=imgs.length; i<iLen; i++) {
src[i] = imgs[i].src;
}
return src;
}
Using Jquery:
var srcList = $('img').map(function() {
return this.src;
}).get();
try
$(document).ready(function () {
var images = $("img");
for (i = 0; i < images.length; i++) {
alert($(images[i]).attr("data-photo-attribution"));
}
});
There you go:
$('.flickr-badge-content li img').each(function(){
var data = $(this).data();
for(var i in data){
$('<li>', {
text: i + ': ' + data[i]
}).appendTo('.flickr-badge-content');
}});
Working Fiddle

Replace an image wherever it is used - Javascript

I'm looking for a way to replace an image that could be used anywhere on a page.
So if we have an example html page like this:
<html>
<head>
</head>
<body>
<img id="1" src="example.com/img/1889.png">
<div style="background: url('example.com/img/1889.png')">
<div>
<a>
<img id="2" src="example.com/img/1889.png">
</a>
</body>
</html>
Where ever - example.com/img/1889.png - appears, it must be replaced with something else.
EDIT
Unfortunately I can't use any javascript libraries. Its for a browser plugin. Nor can I use browser specific APIs
There might be some syntax errors here, but basically just try something like:
<script>
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].src == "oldImg")
imgs[i].src = "newImg";
}
}
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].style.backgroundImage == "oldImg")
divs[i].style.backgroundImage = "newImg";
}
}
</script>
The following code does what you're looking for:
var images = document.querySelectorAll('[src]'), // all image and input elements
styled = document.querySelectorAll('[style]'), // all elements with inline style
iLen = images.length,
sLen = styled.length,
url = 'example.com/img/1889.png', // the string you're searching for
str = 'some/string', // replace with whatever you choose
i;
// check for 'example.com/img/1889.png' in image source
for (i = 0; i < iLen; i += 1) {
if (images[i].src.indexOf(url) !== -1) {
images[i].src = str;
}
}
// check for 'example.com/img/1889.png' in either background or background-image
for (i = 0; i < sLen; i += 1) {
if (styled[i].style.backgroundImage.indexOf(url) !== -1) {
styled[i].style.backgroundImage = 'url(' + str + ')';
}
}
Demo

Categories