Search code examples
javascriptmaterialize

How to fix removing elements in dropdown box (Materialize)


Dropdown boxes are not removed as expected.

After the migration of Materialize from version 0.97 to 1.0.0 the function is not working. Only the text in the dropdown box is removed instead of the complete element.

M.AutoInit();

function removeEdit() {
    var el = document.getElementById("edit");
    el.parentNode.removeChild(el);
}
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
<!-- Record actions -->
  <ul id="actions" class="dropdown-content">
    <li><a href="#" id="edit" onclick="alert('edit')" class="black-text">Edit</a></li>
    <li><a href="#" id="delete" onclick="alert('delete')" class="black-text">Delete</a></li>
  </ul>

 <button type="button" onclick="removeEdit()">Remove element edit</button>
  
  <table class="bordered">
	<thead class='t-h'>
	  <tr class="tr-h" >
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    </thead>
    <tbody class='t-body'>
      <tr id="1" class="tr-d dropdown-trigger" href="#" hover="false" data-target="actions">
	    <td>Row 1, column 1</td>
	    <td>Row 1, column 2</td>
	    <td>Row 1, column 3</td>
      </tr>
      <tr id="2" class="tr-d dropdown-trigger" href="#" hover="false" data-target="actions">
        <td>Row 2, column 1</td>
        <td>Row 2, column 2</td>
        <td>Row 2, column 3</td>
      </tr>
    </tbody>
  </table>
</html>


Solution

  • In removeEdit function, el represents selected <a> so el.parentNode represents selected <li>.

    When you use el.parentNode.removeChild(el), it means that remove child of selected <li> so it removes the <a> tag.

    Change :

    el.parentNode.removeChild(el);
    

    To :

    el.parentNode.remove();
    

    And it removes selected <li>.