How to duplicate display of HTML elements

1

I have 5 images, 3 of them have the same class being displayed in div A.

<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 if condition to compare class='foto' . If the occurrences are identical, then show also in div B.

    
asked by anonymous 25.03.2017 / 11:48

1 answer

2

You can do 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: link

    
25.03.2017 / 12:27