如何在JavaScript中获取span标签的父类名称?

时间:2019-02-01 12:50:39

标签: javascript html dom tags jsdom

<div class="todo"> <h3>Have to understand js DOM</h3>
        <div class="ed-btn">
          <span id="delete" onclick="deleteTodo(event)"><i class="far fa-trash-alt"></i></a>
          </span>`; </div>

const deleteTodo = event => {   console.log(event.currentTarget); };

通过点击我刚刚发现的deleteTodo(event)

      <span id="delete" onclick="deleteTodo(event)"><i class="far fa-trash-alt"></i></a>

但是我如何获得“待办事项”类或h3的内部内容?

2 个答案:

答案 0 :(得分:0)

单击文本“某些文本”以触发侦听器;)

非常简单:

parentElement允许您获取父元素。

className将为您提供节点的类。

innerText将带给您...内部文本;)

const deleteTodo = event => { 
  const target = event.currentTarget;
  const root = target.parentElement.parentElement;
  console.log('root class:', root.className);
  console.log('h3 content:', root.querySelector('h3').innerText); 
};
<div class="todo"> 
  <h3>Have to understand js DOM</h3>
  <div class="ed-btn">
    <span id="delete" onclick="deleteTodo(event)">
      <i class="far fa-trash-alt"></i>
      Some text
    </span>
  </div>
</div>

希望它对您有帮助!

答案 1 :(得分:0)

如果要访问标签的父级,可以使用parentElement方法,如下所示:

document.getElementById("delete").parentElement

more in docs here

但是,您可以直接访问h3或todo元素:

document.getElementsByClassName("todo")

more on that here