0

I'm trying to add and remove a class when a dropdownmenu is being toggled on/off. However, when i run this code locally, i get this error:

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'

I've tried to run the exact same code on JSfiddle, which works just fine. What could this be caused by?

var button = document.getElementById("dropdownMenuButton");
  var element = document.getElementById("dropText");

  window.MutationObserver = window.MutationObserver
  || window.WebKitMutationObserver
  || window.MozMutationObserver;

  var target = document.getElementById("dropdownMenuButton");

  observer = new MutationObserver(function(mutation) {
      if(button.getAttribute("aria-expanded") == 'true') {
      element.classList.add("myEffect");
      }else{
      element.classList.remove("myEffect");
      }
  }),
  config = {
      attributes: true
  };

  observer.observe(target, config);
.myEffect {
position: absolute;
left: 11% !important;
top: -35% !important;
background-color: white;
color: #3faf8f;   
}
<div class="dropdown" id="dropDownDiv">
   <button class="btn btn-secondary dropdown-toggle dropdownButton" type="button" 
   id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" 
   onclick="inputEffect()">
      <span class="dropdownText" id="dropText">Vælg mærke</span><i
      class="fas fa-chevron-down fasDropDown"></i>
 </button>

    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <a class="dropdown-item" href="#">Something else here</a>
    </div>


</div>  
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Why are you getting the same button twice in the code? Once as `button` and once as `target`? – T.J. Crowder Mar 29 '20 at 11:51
  • You showed your script code as being after the elements it referred to, so I put it in a stack snippet (where that's also the case), and it doesn't exhibit the behavior you describe. Perhaps your real code is *before* the elements it uses? That's a common problem [jsFiddle often fixes for people](https://stackoverflow.com/questions/18754685/jquery-script-works-in-jsfiddle-but-not-on-html-page). – T.J. Crowder Mar 29 '20 at 11:53
  • I tried to move the script right before the tag ends, and it seems to have fixed it. – Nissan Pedige Mar 29 '20 at 13:09

0 Answers0