Search code examples
jquerynestedgetelementsbytagname

jQuery replacement for nested getElementsByTagName


I want to use jQuery for nested getElementsByTagName. Many questions deal with nested each, but they veer off into special topics. I can't figure out something that is probably very simple. In pure JavaScript I have:

tables = document.getElementsByTagName('table');
for (var t = 0; t < tables.length; t++)
{
    thisTable = tables[t];
    if (thisTable.id == "specialID")
    {
        inputs = thisTable.getElementsByTagName("input");
        for (var r=0; r < inputs.length; r++)
        {
            thisInput = inputs[r];
            if (thisInput.type == "radio")
            {
                if (thisInput.checked == true)
                {
                    [do stuff]
                    break;
                }
            }
        }
    }
}

Basically this does some testing on certain radio buttons inside of a desired table. The syntax of the nested getElementByTagName is what is causing me problems when I try to convert to jQuery. So far I have this:

$("table").each(function () {
    if (this.id == "specialID")
    {
        $("this:input").each(function () {
            alert("I am here");
            [test for radio and do stuff]
        });
    }
});

The first "each" on tables is working fine and finds all the tables. But the second "each" on inputs doesn't select any of the input controls inside a particular table. I suspect the $("this.input") is incorrect, but I have tried many other things here and I get syntax errors or no better results. What is the right way to form the syntax that lets me iterate over all the inputs inside one of all the tables?


Solution

  • As you can only have one table with the id "specialID", you can do this:

    $("#specialId input").each(function () {
        // ...do stuff with the input
    });
    

    However, in the general case where you might have more than one outer element and want to handle things on inner elements for only some of them:

    $("selector-for-outer-element").each(function () {
        if (/*...some condition...*/) {
            $(this).find("selector-for-inner-elements").each(function() {
                // ...do something with the inner elements
            });
        }
    });
    

    Or if the condition can be expressed as a selector, naturally apply the condition that way instead:

    $("selector-for-outer-element.some-condition selector-for-inner-elements").each(function () {
        // ...do something with the inner elements
    });
    

    ...which is basically what I did with the very first snippet above.