Toggle innerHTML

MySQL picture MySQL · Mar 14, 2012 · Viewed 15.1k times · Source

I've seen various examples come close to what I am looking for, but none of it seems to describe it how I exactly want it. I am a beginner to jQuery, so explanations welcome.

I'm looking for this to toggle the innerHTML from - to +. Anyone know of a way to do this, efficiently?

jQuery/JavaScript

$(document).ready(function() {
            $(".A1").click(function() {
                $(".P1").toggle("slow");
                $(".A1").html("+");
            });
        }); 

HTML

<div class="A1">-</div>
<h2 class="H1">Stuff</h2>
<div class="P1">
Stuffy, Stuffy, Stuffed, Stuffen', Stuffing, Good Luck Stuff
</div>

Thank you, anything relating to switching the inside text of an HTML element shall help. =)

Answer

Andrew Whitaker picture Andrew Whitaker · Mar 14, 2012

How about adding a class that will let you know the expanded/collapsed status?

$(document).ready(function() {
  $(".A1").click(function() {
    var $this = $(this);
    $(".P1").toggle("slow")

    $this.toggleClass("expanded");

    if ($this.hasClass("expanded")) {
      $this.html("-");
    } else {
      $this.html("+");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="A1 expanded">-</div>
<h2 class="H1">Stuff</h2>
<div class="P1">
  Stuffy, Stuffy, Stuffed, Stuffen', Stuffing, Good Luck Stuff
</div>

Example: http://jsfiddle.net/sGxx4/