最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find a parent's ID through a child's ID - Stack Overflow

programmeradmin2浏览0评论

I have a dynamically generated table that will have an ID. If the table has a radio button, when I click on the radio button I need to get that parent table's ID through javascript. How can I do that?

I have a dynamically generated table that will have an ID. If the table has a radio button, when I click on the radio button I need to get that parent table's ID through javascript. How can I do that?

Share Improve this question edited Feb 18, 2011 at 5:45 Michael Mrozek 176k29 gold badges170 silver badges178 bronze badges asked Feb 17, 2011 at 8:36 sreekanth sreekanth 7492 gold badges9 silver badges20 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

With jQuery you can use .closest() or .parent() (though parent only looks up 1 level, whereas .closest() goes up until it find something). I've always found .closest() easier and more robust, as it will work if you change the markup (i.e. you wrap stuff in a <span> or something).

Anyways, here's the jQuery version:

<input type="radio" onlick="var id = $(this).closest('table').attr('id');" />

If you don't use a library, you can do this with just JavaScript as well.

The JavaScript:

function findAncestorByTagName(start, tagName) {
    if (tagName.toUpperCase() === start.nodeName.toUpperCase()) {
        return start;
    }
    else if (start === document.body) {
        return false;
    }
    else {
        return findAncestorByTagName(start.parentNode, tagName);
    }
}

The onclick handler you'll have to add:

<input type="radio" onclick="var par = findAncestorByTagName(this, 'div'); if (par && par.id) { /* use par.id */ }" />

With JQuery can get the Parent of an element by element.parent(). So when you want the id from the parent you can write element.parent().attr("id);

发布评论

评论列表(0)

  1. 暂无评论