Friday, March 3, 2017

Javascript - Find elements by the "for" attribute

            function findLableForControl(el) {
                var idVal = el;
                labels = document.getElementsByTagName('label');
                for( var i = 0; i < labels.length; i++ ) {
                    if (labels[i].htmlFor == idVal)
                        return labels[i];
                }
            }

This function is handy when working with C# CheckBoxList (or really any of the C# lists). When creating javascript to manipulate the list, C# does not provide ID to the label, rows, nor columns. Thus to find the label, only the "for" attribute can be used to search.

Reference

http://stackoverflow.com/questions/285522/find-html-label-associated-with-a-given-input/285575