I have a total of four div
elements and array elements. My goal is to link these two components together effectively.
Specifically, when a user clicks on the first div
element with the class .news, I want to display the values of the first element in the array within the div #selectedNews
.
The main issue I am facing is understanding how to establish a connection between the div elements and the array elements.
Here is the code snippet again:
var newsListData = [
{
"group" : "science",
"title" : "Text 1",
"image" : "images/news1.jpg",
"content" : "Text text text"
},
{
"group" : "science",
"title" : "Text 2",
"image" : "images/news2.jpg",
"content" : "Text text text"
},
{
"group" : "science",
"title" : 'Text 3',
"image" : "images/news3.jpg",
"content" : "Text text text"
},
{
"group" : "economics",
"title" : 'Text 4',
"image" : "images/news4.jpg",
"content" : "Text text text"
}]
var selected;
function elem() {
selected.innerHTML = "";
for (var i = 0; i < this.children.length; i++) {
selected.appendChild(this.children[i].cloneNode(true));
}
}
document.addEventListener("DOMContentLoaded", function() {
var selectedNews = newsListData /* stuck HERE */
for (var i = 0; i < selectedNews.length; i++) {
selectedNews[i].addEventListener("click", elem);
}
selected = document.getElementById("selectedNews")
});
#selectedNews {
border : 1px solid gray;
margin : 10px;
padding : 5px;
}
.news {
background-color: green;
border: 2px solid black;
padding: 4px;
margin-top: 2px;
text-align: center;
}
<div id="newsList">
<input type="text" placeholder="filter..." id="filter"/>
<div class="list">
<div id="0-news" class="news">One</div>
<div id="1-news" class="news">Two</div>
<div id="2-news" class="news">Three</div>
<div id="3-news" class="news">Last one</div>
<article id="selectedNews">
<h1>Titre</h1>
<figure>
<img src="" alt="titre"/>
</figure>
<div id="content">
bla bla
</div>
</article>