使用jquery检索父节点的子节点

Retrieve a childNode of a parent Node with jquery

本文关键字:子节点 父节点 检索 jquery 使用      更新时间:2023-10-12

我有一个html表,它的格式是:

<html>
<table>
    <thead>
        <tr>
            <th idth='keyth'></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class='edit' idtd='keytd'></td>
        </tr>
    </tbody>
</table>
</html>

现在,我希望在jquery中检索从edit类派生的属性"keyth"的内容。示例:

$(".edit") {
    "th_id": this.parentNode.....childNode.getAttribute("idth"),
    //Here I dont know how to achieve the attribute content
});

谢谢你的建议!!!

我终于找到了一个只有Javascript的解决方案:

"th_id":this.parentNode.parentNode.parentNode.childNodes[0].childNodes[0].childNodes[0].getAttribute("idth")

这两种方法都适用于

实时演示

$(function() {
  $(".edit").on("click",function() {  
    var $thWithKeyTd = $("th[idth='keyth']");
    var $parentChild = $(this).closest("table").find("th[idth='keyth']");  
  });            
});    

普通JS

实时演示

window.onload=function() {
  document.querySelector(".edit").onclick=function() {  
    var thWithKeyTd = document.querySelector("th[idth='keyth']");
    console.log(thWithKeyTd.innerHTML);  
  };            
};    

这是一个普通的JS口味,它比jQuery解决方案更快

    "th_id" : this.offsetParent.querySelector('[keyth]')