HTML中指向DOM中元素的标签是什么?

问题描述

在第8行:-它具有element.parentElement.remove(element),这里的元素指的是HTML中的哪个标记

注意:-如果需要,此fiddle代码

JavaScript

    var td4 = document.createElement('td'); 
              td4.setAttribute("id","td4");
              td4.innerHTML = <button 
             onclick=remove(this.parentElement)>X</button> *line4
              tr.appendChild(td4);

    function remove(element){
             element.parentElement.remove(element) **line8**
    }

HTML

<div class='table'>
    <table id="table">
        <th>
             <tr>
                <td>Task</td>
                <td>Date</td>
                <td>Urgency</td>
                <td>Done</td>
            </tr>
        </th>
        <button onclick=clearall()> Clear All </button>
    </table>
</div>

解决方法

您应该使用template strings

// You'll need to access to the tr element.
// Also,I would recommend use const instead of var
const tr = document.querySelector('tr');
const td4 = document.createElement('td'); 
td4.setAttribute("id","td4");
// You'll need to use the parentElement property twice,because the button will be inserted into the 'td' and you need access to the 'tr'
td4.innerHTML = `<button 
onclick=remove(this.parentElement.parentElement)>X</button>`
tr.appendChild(td4);

function remove(element){
  element.parentElement.remove(element)
}
<div class='table'>
    <table id="table">
        <th>
             <tr>
                <td>Task</td>
                <td>Date</td>
                <td>Urgency</td>
                <td>Done</td>
            </tr>
        </th>
        <button onclick=clearAll()> Clear All </button>
    </table>
</div>

了解有关访问DOM here的更多信息。

, element.parentElement.remove(element)中的

元素是td4。 您应该添加console才能轻松打印标签。

    function remove(element){
       console.log(element);
       element.parentElement.remove(element) **line8**
    }

enter image description here