1

I'm trying to build a program to run a function every time I press a button, and output the returned value. To do this, I use the following HTML:

<h2>Test Results:</h2>
    <strong><span id='runs'>0</span> tests</strong><br>
    <div id='testResults'>
        <button id='test' onClick='this.parentNode.innerHTML = initiatePlanB()'>Begin</button>
    </div>

Here's the javascript:

var tests = document.getElementById('runs');
var inner = document.getElementById('testResults').innerHTML;
//Here's the part I can't figure out
var wo = inner.replace(??????, '');
var out = wo + '<br><strong>Test #' + String(Number(tests.innerText) + 1) + '</strong><br>';
tests.innerText = Number(tests.innerText) + 1;
//More stuff here
return out;

Basically, I need either a regex expression, or some other function that can remove any html tag and it's contents.

Radvylf Programs
  • 1,429
  • 1
  • 12
  • 31

1 Answers1

2

Why not just find all buttons using getElementsByTagName('button')

and then remove them all?

var testCount = 0;
var tests = document.getElementById('runs');
var inner = document.getElementById('testResults')

function initiatePlanB() {
  var buttons = inner.getElementsByTagName('button');
  if (buttons) {
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].remove();
    }
  }

  testCount++;
  inner.insertAdjacentHTML('beforeend', '<br><strong>Test #' + testCount + '</strong><br>');

  tests.innerText = testCount;
  //More stuff here
}
<h2>Test Results:</h2>
<strong><span id='runs'>0</span> tests</strong><br>
<div id='testResults'>
  <button id='test' onClick='initiatePlanB()'>Begin</button>
</div>

Though you should probably just hide the buttons, or disable them.

Intervalia
  • 10,248
  • 2
  • 30
  • 60