Home > Mobile >  How to access elements of a clicked button
How to access elements of a clicked button

Time:12-17

New to programming, trying something out for a JS project.

I have three adjacent buttons with the following contents:

for (var i = 0; i < plantButtons; i  ) {
  document.querySelectorAll(".option")[i].addEventListener("click", function() {
    // alert("Plant Button Clicked!");
    plantContainer.style.display = "none";
    plantView.style.display = "flex";
  });
}
<a >
    <img  src="https://via.placeholder.com/50">
    <h3 >Cactus</h3>
    <p >A hardy plant with low watering needs and high sun tolerance.</p>
</a>
<a >
    <img  src="https://via.placeholder.com/50">
    <h3 >Spider Plant</h3>
    <p >A unique plant, adaptable to a variety of conditions.</p>
</a>
<a >
    <img  src="https://via.placeholder.com/50">
    <h3 >Boston Fern</h3>
    <p >A luscious plant with particular requirements. </p>
</a>

When any of the buttons are clicked, they all vanish and a single display appears - in this case, it'll be for one of the three plants on the buttons.

I want to access information from the buttons to help populate the new display afterwards. For example, if they click on the button with the picture of the cactus, I want the following display to have a heading "Cactus" without just hard coding the new header.

I'm not sure about the best way to tackle this, any help would be appreciated.

CodePudding user response:

As some comments are pointing out, you need to separate the block-level elements from your buttons. Anchor tags would be a better option. You could use those in combination with if statements, .innerHTML, and .onclick listeners to populate your new display depending on which anchor is clicked.

  • Related