-1

How can you display one variable multiple times in HTML? When the variable banana increases it only increases for one of the spans using the variable banana.

<!DOCTYPE html>
<html>
<body>

<h3>Example Code</h3>
<button class="button" onclick="Addbanana()">Add 1 Banana</button>
  <p>Bananas = <span id="banana"> 0 </span></p>
  <p>Bananas = <span id="banana"> 0 </span></p>
  <p>Bananas = <span id="banana"> 0 </span></p>


<script>
var banana = 0;
function Addbanana(){
    banana = banana + 1;
    document.getElementById("banana").innerHTML = banana;
}
</script>

</body>
</html> 
Fred
  • 13
  • 2
  • 1
    ID's **MUST** be unique - therefore, the span that getElementById (notice, it is get ELEMENT, singular not plural) gets is the first one only and always – Jaromanda X Dec 27 '16 at 01:38

2 Answers2

1
  1. Instead of using banana IDs, use banana classes. IDs are meant to be unique... but since you have three places where you want to use it, you're better off using classes.
  2. Since you're then using classes, use getElementsByClassName instead of getElementById
  3. This returns an array-like object, so iterate through it, and change the innerHTML as you did before
  4. ???
  5. Profit!
therobinkim
  • 2,500
  • 14
  • 20
0
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>

<h3>Example Code</h3>
<button class="button" onclick="Addbanana()">Add 1 Banana</button>
  <p>Bananas = <span class="banana"> 0 </span></p>
  <p>Bananas = <span class="banana"> 0 </span></p>
  <p>Bananas = <span class="banana"> 0 </span></p>


<script>
var banana = 0;
function Addbanana(){
    banana = banana + 1;
    $(".banana").each(function() {
        $(".banana").html(banana);
    })
}
</script>

</body>
</html> 
evanidul
  • 1
  • 1