简体   繁体   中英

Eventlistener on button to display div

Need to display a div when the user clicks the button.

//html-code

      <div class="col-md-4">
          <h4 class="service-heading">Sociala Medier</h4>
          <p class="text-muted">first line of text.</p>
            <div class="info-text" style="display:none">
              <p class="text-muted">Second line of text.</p>
            </div>
          <button class="info-button"><span>Läs mer </span></button>
        </div>

//js-code

document.getElementByClassName("info-button").addEventListener("click", function(){
   document.getElementByClassName('info-text').style.display = "block";
});

Any advice how I can get this to work? Also tested with onclick but that doesn't work either.

You're passing elements classes to the .getElementById function.
In short, you could change your HTML to this:

<div class="col-md-4">
  <h4 class="service-heading">Sociala Medier</h4>
  <p class="text-muted">first line of text.</p>
  <div id="info-text" style="display:none">
    <p class="text-muted">Second line of text.</p>
  </div>
  <button id="info-button"><span>Läs mer </span></button>
</div>

And it would work

It's actually "getElementsByClassName" you missed the s and it gets a collection so you need to be specific on which one you are targeting. Given your code, you want the first/only element

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

https://jsfiddle.net/cbye0ph9/

document.getElementsByClassName("info-button")[0].addEventListener("click", function(){
   document.getElementsByClassName('info-text')[0].style.display = "block";
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM