Reputation: 157
I wanted to change the style of the second div-element from the innerHTML when i click on the img, but this doesnt work.
function display(restaurantArr, name){
title.innerHTML = `<h2>Available restaurants in ${name}:`
for(let items of restaurantArr){
console.log(items)
main.innerHTML += `
<div class="container">
<p class="containerP">${items.restaurant.name}</p>
<img onclick="editDiv2()" id="imageid" class="imgAdd" src="pngwave.png">
</div>
<div id="someid" class="container2">
<p>Test</p>
<p>Test</p>
<p>Test</p>
</div>
`
}
}
The function where i tried to edit the second div. Although i understand why this doesnt work, it is a visualisation of what i tried to do:
function editDiv2(){
const div2 = document.querySelector('.div2')
div2.style.color = "red";
}
Upvotes: 0
Views: 532
Reputation: 1327
It works for me:
display([{
restaurant: {
name: 'Restaurant Name'
}
}], 'London')
function display(restaurantArr, name) {
title.innerHTML = `<h2>Available restaurants in ${name}:`
for (let items of restaurantArr) {
console.log(items)
main.innerHTML += `
<div class="container">
<p class="containerP">${items.restaurant.name}</p>
<img onclick="editDiv2()" id="imageid" class="imgAdd" src="pngwave.png">
</div>
<div id="someid" class="container2">
<p>Test</p>
<p>Test</p>
<p>Test</p>
</div>
`
}
}
function editDiv2() {
const div2 = document.querySelector('#someid')
div2.style.color = "red";
}
<h2 id="title"></h2>
<div id="main"></div>
Upvotes: 1
Reputation: 561
(function() {
display()
clickEvent()
})();
function display(){
main = document.getElementById("div1")
main.innerHTML = '<div class="container"><p class="containerP">${items.restaurant.name}</p><img id="imageid" class="imgAdd" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/330px-Image_created_with_a_mobile_phone.png"></div><div id="someid" class="container2"><p>Test</p><p>Test</p><p>Test</p></div>'
}
function clickEvent(){
var image = document.getElementById("imageid")
image.addEventListener("click", function(){
const div2 = document.querySelector('.container2')
div2.style.color = "red";
})
}
Where ever you call your display function add a new function for your task and call it below display so it can register dom element its click event listner.
Here is the updated fiddle. https://jsfiddle.net/3h61jdfv/
Upvotes: 1
Reputation: 3323
As this is created dynamically you need to add event dynamically to
add an ID to the Image
<img id="image" class="imgAdd" src="pngwave.png">
then write a click function
const image = document.getElementById("image")
image.addEventListener("click", function(){
const div2 = document.querySelector('.div2')
div2.style.color = "red";
})
Upvotes: 0
Reputation: 1396
<img onclick="div2()"
should be
<img onclick="editDiv2()"
Or the editDiv2 function will not get called.
Upvotes: 1