Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access elements of a clicked button

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 class="option flex-column">
    <img class="plant-img" src="https://via.placeholder.com/50">
    <h3 class="plant-name">Cactus</h3>
    <p class="plant-desc">A hardy plant with low watering needs and high sun tolerance.</p>
</a>
<a class="option flex-column">
    <img class="plant-img" src="https://via.placeholder.com/50">
    <h3 class="plant-name">Spider Plant</h3>
    <p class="plant-desc">A unique plant, adaptable to a variety of conditions.</p>
</a>
<a class="option flex-column">
    <img class="plant-img" src="https://via.placeholder.com/50">
    <h3 class="plant-name">Boston Fern</h3>
    <p class="plant-desc">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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading