开发者

How to find a parent's ID through a child's ID

开发者 https://www.devze.com 2023-02-11 04:48 出处:网络
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.

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?


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

精彩评论

暂无评论...
验证码 换一张
取 消