Search code examples
javascripthtmlecmascript-6ecmascript-5

Alert inner HTML of clicked button


I would like for my function to return me the value of the string inside the button, to later be used in other stuff.

I tried (this).innerHTML and this.innerHTML to extract the string inside of the button and later be used in the js HTML:

<button class="fonts" value="2" onclick="change((this).innerHTML)">Times New Roman</button><br>
<button class="fonts" value="1" onclick="change(this.innerHTML)">Calibri</button><br>
<button class="fonts" value="3" onclick="change(this.innerHTML)">Arial</button>

JS:

function change(){
  alert();
}

I wanted it to alert "Times New Roman" or the other fonts, yet it alerted a blank value.


Solution

  • You should avoid using inline on* handlers (onclick, oninput, etc) and instead use an event listener within your script itself for alerting the elements' text content.

    Check and run the following Code Snippet for a practical example of what I have described above:

    /* JavaScript */
    
    var btns = document.querySelectorAll(".fonts"); // retrieve all buttons
    
    //use forEach() to add a click event listener to each button
    btns.forEach(function (btn) {
      btn.addEventListener("click", function() {
        alert(this.innerHTML);
      });
    });
    <!-- HTML -->
    
    <button class="fonts" value="2">Times New Roman</button><br>
    <button class="fonts" value="1">Calibri</button><br>
    <button class="fonts" value="3">Arial</button>


    You can further shorten the above code by using JavaScript ES6+ instead like this:

    document.querySelectorAll(".fonts").forEach(btn => {
      btn.addEventListener("click", () => alert(btn.innerHTML));
    });
    <button class="fonts" value="2">Times New Roman</button><br><button class="fonts" value="1">Calibri</button><br><button class="fonts" value="3">Arial</button>


    N.B. Do note that if you use the ES6+ approach, you will need to use a JavaScript compiler like Babel to convert your ES6+ syntax into a backwards compatible version of JavaScript on production to support current and older browsers or environments.


    IE11 Compatibility:

    If you are concerned with IE11 compatibility of the forEach() method, you can use a simple for loop instead like this:

    /* JavaScript */
    
    var btns = document.querySelectorAll(".fonts"); // retrieve all buttons
    
    //use forEach() to add a click event listener to each button
    
    for(i=0; i < btns.length; i++) {
      btns[i].addEventListener("click", function() {
        alert(this.innerHTML);
      });
    }
    <!-- HTML -->
    
    <button class="fonts" value="2">Times New Roman</button><br>
    <button class="fonts" value="1">Calibri</button><br>
    <button class="fonts" value="3">Arial</button>