How to duplicate visualization of HTML elements

Asked

Viewed 148 times

1

I have 5 images, and 3 of them have the same class being exhibited on div To.

<div id='A'>

   <img src="https://sites.google.com/site/mplayerplugin/thumbnails/09.jpg" class="figura" />

   <img src="https://sites.google.com/site/mplayerplugin/thumbnails/10.jpg" class="foto" />

   <img src="https://sites.google.com/site/mplayerplugin/thumbnails/11.jpg" class="foto" />

   <img src="https://sites.google.com/site/mplayerplugin/thumbnails/12.jpg" class="foto" />

   <img src="https://sites.google.com/site/mplayerplugin/thumbnails/13.jpg" class="figura" />

</div>

<div id='B'>
   ...
</div>

Based on this logic, I want to create a Script with condition if to compare the class='foto'. If the incidences are identical, then show also in the div B.

1 answer

2


You can do it like this:

// procura as imagens todas
var imagens = document.querySelectorAll('#A img');
var obj = {};

// percorre as imagens
for (var i = 0, l = imagens.length; i < l; i++) {
    var img = imagens[i];
    var classes = img.className.split(' '); // para casos onde há mais que uma classe
    classes.forEach(function(classe) {
        if (!obj[classe]) obj[classe] = []; // inicia a array dessa classe no objeto que separa as classes
        if (obj[classe].indexOf(img) == -1) obj[classe].push(img);
    });
}
var aCopiar = Object.keys(obj).reduce(function(imgs, classe) {
    // lógica para só passar images que aparecem mais que uma vez
	if (obj[classe].length > 2) return imgs.concat(obj[classe]);
	else return imgs;
}, []).filter(function(el, i, arr) {
    return arr.indexOf(el) == i;
});

console.log(aCopiar)

var divB = document.getElementById('B');
aCopiar.forEach(function(img) {
    divB.appendChild(img.cloneNode());
});
#A {
  display: none;
  /* Só para o exemplo */
}
<div id='A'>
  <img src="https://sites.google.com/site/mplayerplugin/thumbnails/09.jpg" class="figura" />
  <img src="https://sites.google.com/site/mplayerplugin/thumbnails/10.jpg" class="foto" />
  <img src="https://sites.google.com/site/mplayerplugin/thumbnails/11.jpg" class="foto" />
  <img src="https://sites.google.com/site/mplayerplugin/thumbnails/12.jpg" class="foto" />
  <img src="https://sites.google.com/site/mplayerplugin/thumbnails/13.jpg" class="figura" />
</div>

<div id='B'></div>

jsFiddle: https://jsfiddle.net/1x6Lu4xc/1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.