语境 :
我想选择属性名称以以下开头的所有元素ng-
.
使用 jQuery,以下链接是最接近此问题的线程:
jQuery - 如何按属性名称开头选择值 https://stackoverflow.com/questions/26657398/jquery-how-to-select-value-by-attribute-name-starts-with .
如何按属性名称开头删除所有属性 https://stackoverflow.com/questions/14731439/how-to-remove-all-attributes-by-attribute-name-starts-with .
然而,第一个使用 jQuery,第二个解决removing问题在于已选择的元素 NOT 选择 .
我试试这个:
document.querySelectorAll('[ng-*]')
它不起作用,而是抛出错误。
这里我使用 querySelectorAll 来获取我想要检查的所有对象。
然后我查看每个返回对象的属性集合
ES6+
const attrStartsWith = (sel,str) => [...document.querySelectorAll(sel)]
.filter(ele => [...ele.attributes]
.filter(({name}) => name.startsWith(str))
.length>0
)
console.log(attrStartsWith("*","ng")); // all
console.log(attrStartsWith("div","ng")); // divs
<div ng-a="a">a</div>
<div ng-b="b">b</div>
<p ng-c="c">c</p>
ES5 及更低版本
function attrStartsWith(sel,str) {
var el = document.querySelectorAll(sel), res=[];
for (var i = 0, n=el.length; i < n; i++){
for (var j=0;j<el[i].attributes.length;j++) {
if (el[i].attributes[j].name.indexOf(str)==0) {
res.push(el[i]);
}
}
}
return res;
}
console.log(attrStartsWith("*","ng")); // all
console.log(attrStartsWith("div","ng")); // divs
<div ng-a="a">a</div>
<div ng-b="b">b</div>
<p ng-c="c">c</p>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)