I have two function. One- that on 'Click' gets the id value. second- gets the sibling data from an id.
I want to combine the two functions, so when i click a div, get that 'id' and display the sibling data from JSON
//this returns sibling data from JSON with id=2
const result = characters.find(item => {
// if this returns `true` then the currently
// iterated item is the one found
return item.id === 2
});
console.log(result);
//this allows me to click the different divs to get their id
var divs = document.querySelectorAll(".characterBox");
for(var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', function (event) {
console.log(this.getAttribute("id"));
});
}
You can put the logic directly into the anonymous function and use this.getAttribute("id")
instead 2
var divs = document.querySelectorAll(".characterBox");
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', function(event) {
const result = characters.find(item => {
return item.id == this.getAttribute("id")
});
console.log(result);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.