Map
HTML
<div class="box">Box</div>
<div class="box">Box</div>
<div class="box">Box</div>
<div class="box">Box</div>
<button onclick="change()">Change box content</button>
<script>
var _consoleLog = console.log;
console.log = function(){
var name = _consoleLog.apply(console,arguments);
var str = "";
for(var index in arguments){
if(Array.isArray(arguments[index])){
arguments[index] = arguments[index].map(function(item){
if(typeof item == "object"){
item = JSON.stringify(item,null,4)+"<br>";
}
return item;
});
str += arguments[index]+" ";
} else if(typeof arguments[index] == "object"){
str += JSON.stringify(arguments[index],null,4);
} else {
str += arguments[index]+" ";
}
}
document.querySelector("body").innerHTML += ("<div>"+str+"</div>");
}
</script>
JavaScript
var myMap = new Map(),
box = document.querySelectorAll(".box");
for(var i = 0; i < box.length; i++){
//Associate the box content with the relevant DOM elements
myMap.set(
document.querySelectorAll(".box")[i],
console.log({content: "This is a box " + i});
);
}
window.change = function change(){
//Replace each element with the value's content
myMap.forEach(function(value,key){
key.innerHTML = value.content;
});
}