As shown in the picture above, when the first element value is 7, If I click, I want to output 7 in console.log.
var container1 = document.createElement('div')
container1.className = 'container1';
document.body.appendChild(container1);
for(var index = 0;index < 20 ; index++){
var aa = document.createElement('span')
aa.innerHTML = card1[index];
container1.appendChild(aa);
aa.className = 'card'+index;
aa.addEventListener('click',clickEvent)
}
function clickEvent(){
//What code should I use?
}
how are you?
Try this:
function clickEvent(evt){
console.log(evt.target.innerHTML)
}
If you have provided the HTML and CSS too then it will be a direct answer to your need but a similar approach can be done using this keyword which print innerHTML of each span tag on click
function paret(reed) {
console.log(reed.innerHTML)
}
div {
display: flex;
justify-content: space-between;
}
span {
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 160px;
background-color: red
}
<div>
<span onclick="paret(this)">7</span>
<span onclick="paret(this)">17</span>
<span onclick="paret(this)">9</span>
<span onclick="paret(this)">8</span>
<span onclick="paret(this)">5</span>
</div>
For this you could use the textContent property of HTML elements in JavaScript. To complete this you would also need to pass the event into your clickEvent function. Click events have a event.target, which is the HTML node that was clicked. The event
var container1 = document.createElement('div')
container1.className = 'container1';
document.body.appendChild(container1);
for(var index = 0;index < 20 ; index++){
var aa = document.createElement('span')
aa.innerHTML = card1[index];
container1.appendChild(aa);
aa.className = 'card'+index;
aa.addEventListener('click',clickEvent)
}
function clickEvent(event){
//What code should I use?
let clickedBox = event.target;
console.log(clickedBox.textContent);
}
As far as I know, this should work like you're intending. I haven't worked with the front-end side of JS lately, so correct me if I'm wrong.