Filter getElementsByTagName list by option values

拜拜、爱过 提交于 2019-12-12 02:18:32

问题


I'm using getElementsByTagName to return all the select lists on a page - is it possible to then filter these based upon an option value, ie of the first or second item in the list?

The reason is that for reasons I won't go into here there are a block of select lists with number values (1,2,3,4,5 etc) and others which have text values (Blue and Black, Red and Black etc) and I only want the scripting I have to run on the ones with numerical values. I can't add a class to them which would more easily let me do this however I can be certain that the first option value in the list will be "1".

Therefore is there a way to filter the returned list of selects on the page by only those whose first option value is "1"?


回答1:


I am pretty sure that there is a better solution, but for the moment you can try something like:

var allSelect = document.getElementsByTagName("select");

var result = filterBy(allSelect, 0/*0 == The first option*/, "1"/* 1 == the value of the first option*/);


function filterBy(allSelect, index, theValue) {
    var result = [];
    for (var i = 0; i < allSelect.length; i++) {
        if(allSelect[i].options[index].value == theValue ) {
            result.push(allSelect[i]);
        }    
    }
    return result;            
}



回答2:


I managed to get this working by wrapping a simple IF statement around the action to be performed (in this case, disabling options) as follows:

    inputs = document.getElementsByTagName('select');

    for (i = 0; i < inputs.length; i++) {
      if (inputs[i].options[1].text == 1) {
      // perform action required
      }
    }

No doubt there is a slicker or more economic way to do this but the main thing is it works for me.



来源:https://stackoverflow.com/questions/11831964/filter-getelementsbytagname-list-by-option-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!