3

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?

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
sreekanth
  • 709
  • 2
  • 9
  • 20

2 Answers2

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 */ }" />
Dan Beam
  • 3,632
  • 2
  • 23
  • 27
0

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

w1ng
  • 324
  • 1
  • 2
  • 11