Search code examples
javascriptclickinnerhtml

How to change button text to innerHTML of clicked list item


I've been searching but all i find are JQuery answers, i'm looking for a vanilla JS solution.

When a list-item gets clicked, i want the button text to change into the innerHTML of that clicked li.

I'm getting close, but somehow the current variable only returns the innerHTML of the last list-item.

So what do I need to change to get the innerHTML of the clicked li as button text?

JS-Fiddle here

var clickHandler = function() {

  document.getElementById('dropbtn').innerHTML = current.innerHTML;

};

var dropdown = document.getElementById('dropdown');
var filterItem = dropdown.getElementsByTagName('LI')

for (var i = 0; i < filterItem.length; i++) {
  var current = filterItem[i];
  current.addEventListener('click', clickHandler, false);

}
<div class="dropdown">
  <a id="dropbtn">Menu</a>
  <ul id="dropdown" class="dropdown-content">
    <li>ALL</li>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
  </ul>
</div>

I cut out the css of this dropdown to keep things clear.


Solution

  • As stated in the comments change

    document.getElementById('dropbtn').innerHTML = current.innerHTML;
    

    To

    document.getElementById('dropbtn').innerHTML = event.target.innerHTML;
    

    var clickHandler = function() {
    
      document.getElementById('dropbtn').innerHTML = event.target.innerHTML;
    
    };
    
    var dropdown = document.getElementById('dropdown');
    var filterItem = dropdown.getElementsByTagName('LI')
    
    for (var i = 0; i < filterItem.length; i++) {
      var current = filterItem[i];
      current.addEventListener('click', clickHandler, false);
    
    }
    <div class="dropdown">
      <a id="dropbtn">Menu</a>
      <ul id="dropdown" class="dropdown-content">
        <li>ALL</li>
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
      </ul>
    </div>