How to find parent id using child id

I have a dynamically generated table that will have an ID. If there is a switch in the table, when I click on the switch, I need to get the identifier of the parent table through javascript. How can i do this?

+3
source share
2 answers

With jQuery, you can use .closest()or .parent()(although the parent view is only 1 level, while it .closest()rises until it finds something). I have always found .closest()it simpler and more reliable, as it will work if you change the layout (i.e. you transfer the material to <span>or something else).

Anyway, here is the jQuery version:

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

, JavaScript.

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);
    }
}

onclick, :

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

JQuery element.parent(). , , element.parent(). Attr ("id);

0

Source: https://habr.com/ru/post/1792739/


All Articles