用属性名称选择元素的普通js开头为 [英] plain js to select element by attribute name starts with
本文介绍了用属性名称选择元素的普通js开头为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
-
HTML
HTML
<div ng-me=""></div>
<div ng-you=""></div>
<p ng-you=""></p>
我要选择所有具有属性的元素名称以 ng-
开头。
I want to select all elements which has attribute name starts with ng-
.
使用jQuery,以下链接是与此问题最接近的线索:
Using jQuery , the following links are the closest threads to this issue :
但是,第一个使用jQuery,第二个使用删除已已选择的元素而不是选择的问题。
However ,the first uses jQuery , and the second resolves removing issue of already selected elements NOT selection .
我尝试这样做:
document.querySelectorAll('[ng-*]')
它确实它无法工作,但是会引发错误。
And it does not work , but rather, it throws error.
推荐答案
在这里,我使用querySelectorAll获取所有要检查的对象。
Here I use querySelectorAll to get all objects that I want to check.
然后我查看每个返回对象的属性集合
Then I look at the attributes collection of each returned object
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>
这篇关于用属性名称选择元素的普通js开头为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文