javascript – Standard way of getting textContent of clicked dropdown element not working-ThrowExceptions

Exception or error:

I have a simple dropdown list and cant seem to get the textContent of the clicked element. Should be fairly simple but apparently one can make a science out of it. So any help would be appreciated.

document.querySelector('#myDropdown').addEventListener('click', function() { 

    console.log(this.textContent); 
    var er = document.querySelector("#myDropdown");
	  var result = er.value;
	  console.log(result);
	
	  var e = document.getElementById("myDropdown");
    var text = e.options[e.selectedIndex].text;
    console.log(text);
    
})
<div class="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <div class="dropdown">
    <button class="dropbtn">Dropdown
      <i class="fa fa-caret-down"></i>
    </button>
    <div id="myDropdown" class="dropdown-content">
      <a>Link 1</a>
      <a>Link 2</a>
      <a>Link 3</a>
    </div>
  </div>
</div>

The first consolelog logs all elements of the dropdown list, the second “undefined” and the third says “Uncaught TypeError”. Is it because my dropdown is not made with the traditional select/ options style ? Thanks and nice Sunday.

How to solve:

Inside an event listener which is a function, this inside it will refer to the element the listener was attached to. Here, that’s the #myDropdown <div>.

The e.options[e.selectedIndex] method only works for <select>s.

If you want to identify which link was clicked, first make sure the event.target (the clicked element) is an <a>, then extract the event.target‘s textContent:

document.querySelector('#myDropdown').addEventListener('click', function(event) {
  if (event.target.matches('a')) {
    console.log(event.target.textContent);
  }
})
<div class="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <div class="dropdown">
    <button class="dropbtn">Dropdown
      <i class="fa fa-caret-down"></i>
    </button>
    <div id="myDropdown" class="dropdown-content">
      <a>Link 1</a>
      <a>Link 2</a>
      <a>Link 3</a>
    </div>
  </div>
</div>

You do need to check if the clicked element is an <a> first – otherwise, clicks on the #myDropdown but not on an inner <a> will result in logs too, which you don’t want.

Leave a Reply

Your email address will not be published. Required fields are marked *