Button onclick function adds class to div

Viewed 22

I'm looking to add the class '.expanded' to #infoBox when the user clicks on the button (which is located inside of the div), which have onclick="expand" on it.

<div id="infoBox" class="" onclick="expand">
    <aside>
        <h4>Kontakt</h4>
        <p>Har du brug for grafisk assistance, i form af råd og vejledning, eller brug for hjælp til design af grafik? Fyr mig en besked!</p>
    </aside>
                
    <button onClick="expand" class="primaryBtn noMovement">Kontakt</button>
</div>

After searching for solutions, I see a lot of jQuery-solutions, but isn't it possible to create with plain javascript?

Out of my noobie experience, I tried the following two javascript executions, but with no luck:

function expand() {
    document.getElementById("infoBox") {
        classList.add("expanded");
    }
}

function expand() {
    document.getElementsById("infoBox").classList.add("expanded");
}
2 Answers

Your second approach is almost correct, you just need to modify getElementsById to getElementById (Element without s).

The way you're calling onclick="expand" need to be like onclick="expand()" (execute expand on onclick event).

function expand() {
  document.getElementById("infoBox").classList.add("expanded");
}
<div id="infoBox" class="" onclick="expand()">
  <aside>
    <h4>Kontakt</h4>
    <p>Har du brug for grafisk assistance, i form af råd og vejledning, eller brug for hjælp til design af grafik? Fyr mig en besked!</p>
  </aside>

  <button onClick="expand()" class="primaryBtn noMovement">Kontakt</button>
</div>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
  box-sizing: border-box;
}
</style>
</head>
<body>

<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is a DIV element.
</div>

<script>
function myFunction() {
   var element = document.getElementById("myDIV");
   element.classList.add("mystyle");
}
</script>

</body>
</html>

here is a working snippet from w3schools. get the element to a variable first

Related