Search code examples
javascriptjqueryformsjquery-selectorsdom-traversal

Find control in javascript or JQuery


I have a dynamic html table generated using javascript. the table contains diffrent controls like textbox,dropdown box which has custom attributes.How can I loop through all the controls present inside this table and find the control whose custom attribute matches to some value?


Solution

  • This will give you all the form elements inside your table (:input selector):

    var $formElements = $('#tableid').find(':input');
    

    You can filter with an attribute selector:

    //will select every form element having a data-custom attribute set to 5
    var $formElements = $('#tableid').find(':input[data-custom="5"]');
    

    Please see the jsFiddle Demo. For my examples I used HTML5 data- attributes, but the code will work with any attribute you need.

    OR you can use the filter() method to write a function that filters your elements:

    var $formElements = $('#tableid').find(':input').filter(function () {
        return $(this).attr('data-custom') == '5';
    });
    

    jsFiddle Demo with filter()