Home > other >  click event on each button of a class
click event on each button of a class

Time:11-26

First time writing here. I am new to programming and here I am learning a lot of things!

Now, I want write this: for each clicked element of a class create a var with nextSibling's text and show it somewhere. The following code is for sure full of error, but it is what i thought:

//wants to create an accessible variable (even out the function)
//from a sibling element's text.
$(".games").click(function(){
myVar = this.next("p").html;})

the HTML situation is this:

<button class="games">GAME ONE</button><p> THESE ARE THE DETAILS OF THE GAME 1</p>
<button class="games">GAME TWO</button><p> THESE ARE THE DETAILS OF THE GAME 2</p>
<div id="show"> I will show the content of paragraphs here if one of the two buttons is clicked</div>

I thank everybody because - I repeat - I am learning a lot here.

CodePudding user response:

function buttonClick(button){
    document.getElementById("show").innerHTML=button.innerHTML
}
<button class="games" onclick="buttonClick(this)">GAME ONE</button><p> THESE ARE THE DETAILS OF THE GAME 1</p>
<button class="games" onclick="buttonClick(this)">GAME TWO</button><p> THESE ARE THE DETAILS OF THE GAME 2</p>
<div id="show"> I will show the content of paragraphs here if one of the two buttons is clicked</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const button = document.querySelector(".games")
button.addEventListener('click', () => {

  myText = document.querySelector('p').innerHTML = 'your text : I will show the content of paragraphs here if one of the two buttons is clicked ' 
) 

<button class="games">GAME ONE</button><p> THESE ARE THE DETAILS OF THE GAME 1</p>
<button class="games">GAME TWO</button><p> THESE ARE THE DETAILS OF THE GAME 2</p>
<div id="show"> <p> I will show the content of paragraphs here if one of the two buttons is clicked  </p></div>
  • Related