如何在纯JavaScript中使用类似jQuery的选择器

我在寻找的是:

var arrinput = $('input[name$="letter"]') 

如何将其从jQuery样式更改为纯javascript样式?

所以我想要标签,其name以“letter”结尾。


我改变了一些代码…我的浏览器不支持querySelector和FYI我在c#winforms上使用webbrowser组件

尝试:

 var items = document.getElementsByTagName('input'); for (var i=0; i 

对于现代浏览器:

document.querySelector('input[name$=letter]');

将返回第一场比赛。

document.querySelectorAll('input[name$=letter]');

将返回匹配列表。

我怀疑如果你查看jquery源代码,它会使用document.querySelector[All]

这是一个老post,但我搜索了一个类似的解决方案,我还没有找到它。

所以我做了一点function(它是可以优化的):

 /** * Searches and finds the parent node for a dom object * * @examples: * getParent(elem, 'div') // The first div parent found * getParent(elem, 'div[id]') // The first div parent with an id found * getParent(elem, 'div[id="toto"]') // The first div parent with id equals toto found * getParent(elem, 'div[id=^="toto"]') // The first div parent with id start by toto found * getParent(elem, 'div[id=$="toto"]') // The first div parent with id end by toto found * getParent(elem, 'div[id=*="toto"]') // The first div parent with id contains toto found * * @param domObject elem * @param string [target] * @return domObject or null */ function getParent(elem, target) { if(target == null) return elem.parentNode; var elem_name = target, attr_name = null, attr_value = null, compare_type = null, match_val = target.match(/\[.+[^\[\]]\]$/i); if(match_val != null) { elem_name = elem_name.replace(match_val[0], ''); var expr = match_val[0].substr(1, match_val[0].length-2), tmp = expr.split('='); attr_name = tmp[0]; if(tmp.length == 2) { attr_value = tmp[1].toLowerCase(); attr_value = attr_value.replace(/(\'|\")+/ig, ''); if(attr_name.match(/\^$/)) compare_type = 'begin'; else if(attr_name.match(/\*$/)) compare_type = 'all'; else if(attr_name.match(/\$$/)) compare_type = 'end'; else compare_type = 'simple'; if(compare_type != 'simple') attr_name = attr_name.substr(0, attr_name.length-1); } } var parent = elem.parentNode; do { if(parent.nodeName.toUpperCase() == elem_name.toUpperCase()) { if(attr_name != null) { var attribute = parent.getAttribute(attr_name).toLowerCase(); if(attribute != null && attribute != '') { if(attr_value == null) return parent; if(compare_type == 'simple' && attribute == attr_value) return parent; if(compare_type == 'begin' && attribute.match(eval('/^'+attr_value+'/ig'))) return parent; if(compare_type == 'end' && attribute.match(eval('/'+attr_value+'$/ig'))) return parent; if(compare_type == 'all' && attribute.match(eval('/'+attr_value+'/ig'))) return parent; } } else { return parent; } } parent = parent.parentNode; } while(parent != null); return null; }